How to execute PowerShell commands from a batch file?
This is what the code would look like in a batch file(tested, works):
powershell -Command "& {set-location 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}"
Based on the information from:
http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/
Type in cmd.exe Powershell -Help
and see the examples.
This solution is similar to walid2mi (thank you for inspiration), but allows the standard console input by the Read-Host cmdlet.
pros:
- can be run like standard .cmd file
- only one file for batch and powershell script
- powershell script may be multi-line (easy to read script)
- allows the standard console input (use the Read-Host cmdlet by standard way)
cons:
- requires powershell version 2.0+
Commented and runable example of batch-ps-script.cmd:
<# : Begin batch (batch script is in commentary of powershell v2.0+)@echo off: Use local variablessetlocal: Change current directory to script location - useful for including .ps1 filescd %~dp0: Invoke this file as powershell expressionpowershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))": Restore environment variables present before setlocal and restore current directoryendlocal: End batch - go to end of filegoto:eof#># here start your powershell script# example: include another .ps1 scripts (commented, for quick copy-paste and test run)#. ".\anotherScript.ps1"# example: standard input from console$variableInput = Read-Host "Continue? [Y/N]"if ($variableInput -ne "Y") { Write-Host "Exit script..." break}# example: call standard powershell commandGet-Item .
Snippet for .cmd file:
<# : batch script@echo offsetlocalcd %~dp0powershell -executionpolicy remotesigned -Command "Invoke-Expression $([System.IO.File]::ReadAllText('%~f0'))"endlocalgoto:eof#># here write your powershell commands...