Skip to content

Instantly share code, notes, and snippets.

@nickadam
Created March 31, 2020 16:38
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save nickadam/2a0db76bf3e32008a934ee3f675e8776 to your computer and use it in GitHub Desktop.
Save nickadam/2a0db76bf3e32008a934ee3f675e8776 to your computer and use it in GitHub Desktop.
[ps1_to_cmd] Convert a multiline PS1 script to a single line cmd file #PowerShell
$s = Get-Content script.ps1 | Out-String
$j = [PSCustomObject]@{
"Script" = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($s))
} | ConvertTo-Json -Compress
$oneline = "[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(('" + $j + "' | ConvertFrom-Json).Script)) | iex"
$c = [convert]::ToBase64String([System.Text.encoding]::Unicode.GetBytes($oneline))
("Powershell -NoLogo -NonInteractive -NoProfile -ExecutionPolicy Bypass -Encoded " + $c) | Out-File -Encoding Default script.cmd
@SteemerSon
Copy link

Works great, thanks

@delinter
Copy link

TIL, PowerShell can run encoded scripts. This is really clever. Good work dude!

@tarcisiomiranda
Copy link

very good, this save my life

@FyeCobain
Copy link

Works like a charm. Thank you! 👍

@pda8888
Copy link

pda8888 commented Jul 31, 2023

great job.
but...
how about cli parameter?
param (
[string]$param1
[string]$param2
)

@DanAmoyal
Copy link

Very cool. I needed this to properly send ps1 commands from a java test framework without drowning in a bog of escape characters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment