Skip to content

Instantly share code, notes, and snippets.

@martin77s
Last active April 4, 2021 13:35
Show Gist options
  • Save martin77s/6dfcb95d381b9c033db116fd0f81c3ab to your computer and use it in GitHub Desktop.
Save martin77s/6dfcb95d381b9c033db116fd0f81c3ab to your computer and use it in GitHub Desktop.
Embed PowerShell code in a batch file
@ECHO off
@setlocal EnableDelayedExpansion
@goto label1
@echo this lines should not be printed
@echo and this whole block (lines 4-8) can actually be removed
@echo I added these just for Charlie22911
@:label1
@set LF=^
@SET command=#
@FOR /F "tokens=*" %%i in ('findstr -bv @ "%~f0"') DO SET command=!command!!LF!%%i
@powershell -noprofile -noexit -command !command! & goto:eof
# *** POWERSHELL CODE STARTS HERE *** #
Write-Host 'This is PowerShell code being run from inside a batch file!' -Fore red
$PSVersionTable
Get-Process -Id $PID | Format-Table
@Charlie22911
Copy link

I seem to be having trouble with this when using goto.
For example, the following results in “cannot find the batch label specified”. Any ideas?
@@:start
@@goto start

@martin77s
Copy link
Author

I seem to be having trouble with this when using goto.
For example, the following results in “cannot find the batch label specified”. Any ideas?
@@:start
@@goto start

The double at's (@) were just incase the original batch included one in the first place.
You can change it to use only one. I'll fix the code above to reflect it.

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