Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute PowerShell commands from a batch file?

I have a PowerShell script to add a website to a Trusted Sites in Internet Explorer:

set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" set-location ZoneMap\Domains new-item TESTSERVERNAME set-location TESTSERVERNAME new-itemproperty . -Name http -Value 2 -Type DWORD 

I want to execute these PowerShell commands from a batch file. It seems simple when I have to run a single command, BUT in this case I have a sequence of related commands. I want to avoid creating a separate file for the PS script to be called from the batch - everything must be in the batch file.

The question is: How to execute PowerShell commands (or statements) from a batch file?

like image 327
Andrei Avatar asked May 17 '11 21:05

Andrei


People also ask

Can you run PowerShell commands from cmd?

To run Powershell commands from the command prompt or cmd, we need to call the PowerShell process PowerShell.exe.

How do I make a PowerShell script executable?

To change the execution policy to run PowerShell scripts on Windows 10, use these steps: Open Start. Search for PowerShell, right-click the top result, and select the Run as administrator option. Type the following command to allow scripts to run and press Enter: Set-ExecutionPolicy RemoteSigned.

How do you run a PowerShell script?

In File Explorer (or Windows Explorer), right-click the script file name and then select "Run with PowerShell". The "Run with PowerShell" feature starts a PowerShell session that has an execution policy of Bypass, runs the script, and closes the session.

How do I run multiple PowerShell commands in one script?

Using AND(&&) Operator You can use this in both CMD and Powershell. Usage: command1 && command2 && command3 [&& command4 ...] Here, if command2 runs only if command1 succeeded.


2 Answers

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/

like image 119
Hassan Voyeau Avatar answered Oct 01 '22 03:10

Hassan Voyeau


Type in cmd.exe Powershell -Help and see the examples.

like image 21
Emiliano Poggi Avatar answered Oct 01 '22 05:10

Emiliano Poggi