PowerShell Batch Files


This entry is part 6 of 9 in the series PowerShell

How would you run a PowerShell script from a batch file? The batch file is a text file that has one or more commands that are to be executed one-by-one from the top down. Using batch files can be much more efficient than typing the commands in one at a time at the console.

There is a post over at StackOverflow called How to run a PowerShell script from a batch file.

To do this you would first start PowerShell as Administrator. You will need a simple script file to test this. The file is a simple text file with the extension .ps1. To test it you could just insert a couple of lines. You could use Write-Host “Hello World”. You could also use Write-Output ‘Hello There World’. Write-Host allows you to set the background or foreground color like this: Write-Host “hello” -backgroundcolor magenta.

To illustrate this, I’ll keep the batch file as simple as possible to start. I’ll just use Write-Output and Write-Host followed by a text string. For example Write-Output “Hello World”. Below is the line of code in PowerShell that executes the text file, followed by the output.

PS C:\temp> Powershell.exe -executionpolicy remotesigned -File c:\temp\hello.ps1
Hi
Line 2
output
PS C:\temp>
Series Navigation<< PowerShell CommandletsPowerShell Commenting >>