Skip to content

Instantly share code, notes, and snippets.

@fearthecowboy
Created March 9, 2021 21:02
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 fearthecowboy/d4492850e0b15e0c7279c5aa449194c1 to your computer and use it in GitHub Desktop.
Save fearthecowboy/d4492850e0b15e0c7279c5aa449194c1 to your computer and use it in GitHub Desktop.
This file can be saved as .ps1 or .cmd and works for both. Even supports cmdline arguments!
@(echo off) > $null
if #ftw NEQ '' goto :init
($true){ $Error.clear(); }
# unpack arguments if they came from CMD
$hash=@{};
get-item env:argz* |% { $hash[$_.name] = $_.value }
if ($hash.count -gt 0) {
$args=for ($i=0; $i -lt $hash.count;$i++) { $hash["ARGZ[$i]"] }
}
# powershell script starts here
write-host -nonewline "There are ($($args.count)) arguments: "
$args |% { write-host -nonewline -fore cyan "$_ ," }
write-host ""
return
# powershell script ends here
<#
:set
set ARGZ[%i%]=%1&set /a i+=1 & goto :eof
:unset
set %1=& goto :eof
:init
if exist $null erase $null
:: add the cmdline args to the environment so powershell can use them
set /a i=0 & for %%a in (%*) do call :set %%a
:: find the pwsh/powershell.exe
set POWERSHELL_EXE=
for %%i in (pwsh.exe powershell.exe) do (
if EXIST "%%~$PATH:i" set POWERSHELL_EXE=%%~$PATH:i & goto :gotpwsh
)
:gotpwsh
:: Run this file as a powershell script
%POWERSHELL_EXE% -noprofile -executionpolicy unrestricted -command "iex (get-content %~dfp0 -raw)#"
set _EXITCODE=%ERRORLEVEL%
:: clear out the argz
@for /f "delims==" %%_ in ('set ^| findstr -i argz') do call :unset %%_
:: we're done
exit /b _EXITCODE
goto :eof
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment