Quantcast
Channel: TechNet Blogs
Viewing all articles
Browse latest Browse all 34890

Embed PowerShell code in a batch file

$
0
0

In a certain scenario, I needed a batch file (bat or cmd extension) that runs PowerShell code, and I could have only one file, so I couldn't go with the easy way of a batch file calling PowerShell.exe with the -File parameter specifying the path to a ps1 file.

For this, I created a special batch file with a header that reads the contents of itself, excludes the lines that have the batch code (lines stat start with @@) and then runs the rest in PowerShell.

Here is the batch template, just replace the lines below the comment that says "POWERSHELL CODE STARTS HERE" with your PowerShell code.

@@ECHO off
@@setlocal EnableDelayedExpansion
@@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

Though not intended, it's another way of bypassing the ExecutionPolicy even if it's set in Group Policy, since the code is run as commands and not a script file.

HTH,

Martin.


Viewing all articles
Browse latest Browse all 34890

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>