-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConvert-PowerShellToBatch.ps1
More file actions
46 lines (39 loc) · 1.69 KB
/
Copy pathConvert-PowerShellToBatch.ps1
File metadata and controls
46 lines (39 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function Convert-PowerShellToBatch
{
<#
.SYNOPSIS
Wraps a PowerShell script as a self-contained batch file.
.DESCRIPTION
Reads a .ps1 file, base64-encodes it as UTF-16LE, and writes a .bat file alongside it
that runs the encoded payload with 'powershell.exe -encodedCommand'. The resulting .bat
can be double-clicked or called from cmd.exe without needing to change the execution
policy or worry about file associations.
Accepts pipeline input, including from Get-ChildItem, so you can batch-convert an
entire folder of scripts in one command.
.PARAMETER Path
Path to the .ps1 file to convert. Aliases: FullName (compatible with Get-ChildItem output).
.EXAMPLE
Convert-PowerShellToBatch -Path "C:\Scripts\Deploy.ps1"
Creates C:\Scripts\Deploy.bat alongside the original script.
.EXAMPLE
Get-ChildItem C:\Scripts -Filter *.ps1 | Convert-PowerShellToBatch
Converts every .ps1 in the folder to a matching .bat file.
.NOTES
The output .bat uses 'powershell.exe' (Windows PowerShell 5.x), not 'pwsh'.
If your script requires PowerShell 7, adjust the executable in the generated file.
The -NoExit flag is included so the window stays open after the script finishes.
#>
param
(
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[string]
[Alias("FullName")]
$Path
)
process
{
$encoded = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((Get-Content -Path $Path -Raw -Encoding UTF8)))
$newPath = [Io.Path]::ChangeExtension($Path, ".bat")
"@echo off`npowershell.exe -NoExit -encodedCommand $encoded" | Set-Content -Path $newPath -Encoding Ascii
}
}