Skip to content

Instantly share code, notes, and snippets.

@Halkcyon
Created February 9, 2021 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Halkcyon/04f499fd7e060e130a34a2c5b4d3c2f2 to your computer and use it in GitHub Desktop.
Save Halkcyon/04f499fd7e060e130a34a2c5b4d3c2f2 to your computer and use it in GitHub Desktop.
A PowerShell Batch wrapper
# 2>NUL & @CLS & PUSHD "%~dp0" & "%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -nol -nop -ep bypass "[IO.File]::ReadAllText('%~f0')|iex" & POPD & EXIT /B
<#
@
Stops a command from echoing to the console host.
# 2>NUL & @CLS
This allows us to comment out the batch wrapper part from the powershell script and eats the cmd.exe error since # is not a command or control character.
PUSHD "%~dp0"
Ensure our working directory is the same as the script's root so we can use $PWD accurately in the script (since $PSScriptRoot will be unavailable).
"%SystemRoot%\[...]\powershell.exe"
Ensure we're executing the right interpreter. If this is compromised, there's no hope for the system anyways.
-nol -nop -ep bypass
-NoLogo -NoProfile -ExecutionPolicy Bypass
"[IO.File]::ReadAllText('%~f0')|iex"
-Command "Invoke-Expression -Command ([System.IO.File]::ReadAllText('%~f0'))"
%~f0 will evaluate to the script's fully-qualified name. This piece is what actually executes our script with Invoke-Expression. powershell.exe will not execute files without a .ps1 extension so this piece is necessary without creating an intermediate temp file.
POPD
Resets the working directory.
EXIT /B
Allows %ERRORLEVEL% to be reflected properly.
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment