Skip to content

Instantly share code, notes, and snippets.

@fearthecowboy
Last active March 3, 2021 22:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fearthecowboy/bf196c66e5854d0be9c9f1a3e05d0993 to your computer and use it in GitHub Desktop.
Save fearthecowboy/bf196c66e5854d0be9c9f1a3e05d0993 to your computer and use it in GitHub Desktop.
This file is a legal .cmd script and a legal powershell script.
@(echo off) > $null
set null( New-Module -ScriptBlock { function goto { }; function :{ } } )#=
: # This file is both a .cmd script and a powershell script. if you save it as
: # sample.cmd and run it it from cmd.exe it will run the same as if you
: # saved it as sample.ps1 and run it.
: # well, in this case, I added some echos on the cmd side...
goto :CMDSTART
write-host -fore green this is powershell
write-host -fore blue thanks!
: CMDSTART <#
doskey #=rem
if exist $null erase $null
echo this is cmd
echo and now I will call this same file as a powershell script
:: you can use powershell or pwsh, it's all good
powershell -noprofile -executionpolicy unrestricted -command "iex (get-content -raw %~dfp0) "
echo and finishing as cmd
: #>
@(echo off) > $null
if #foo NEQ '' goto :CMDSTART
($true){}
# powershell script starts here
write-host -fore green hi from powershell
return
:CMDSTART
:: do anything we need to before calling into powershell
if exist $null erase $null
echo hi from cmd.
powershell -noprofile -executionpolicy unrestricted -command "iex (get-content -raw %~dfp0) "
@fearthecowboy
Copy link
Author

I worked a bit more and made it better!

The second example is much less tricky!

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