How to start a PowerShell Script from a Batch File
In last week’s PowerShell class in Phoenix, we had a last
minute question. It involved trying to
simplify the launching of a PowerShell script for users. Having end users working with PowerShell has
long been a cumbersome task. End users
like a GUI. We can put a GUI interface
on top of our code, but it is difficult to do manually or you need a third
party solution. When you build a GUI, it
also takes an additional skill set that most IT Pros do not have.
We decided to go with a batch file. Yes, I know.
Old tech but we will give it new life.
Here is our test code for this project. We saved this file as
c:\ps\Test1.ps1.
Write-Host "I
work!!!" -BackgroundColor DarkMagenta
Yes, I know. Not
exactly exciting. The purpose of this is
to get it to launch with a batch file.
We looked at the PowerShell.exe
Command-Line Help (https://docs.microsoft.com/en-us/powershell/scripting/core-powershell/console/powershell.exe-command-line-help?view=powershell-5.1)
to see how to launch PowerShell with a script from the command line at the same
time. We came up with:
PowerShell.exe –File C:\PS\Test1.ps1
We saved this command line into a batch file in the same
directory as the script and was able to launch it from a desktop shortcut
icon. Right now, this is a viable
option.
What about using parameters?
This is a bit more difficult. The
original objective was to do it from a DOS command prompt, but when we add
parameters, the process is just as complex as doing it PowerShell if not more. Here is our new code.
Param ($ComputerName)
Write-Host "I
work!!!" -BackgroundColor DarkMagenta
Write-Host $ComputerName
Again, I know. Real
advanced. This is what our batch file
looks like now:
PowerShell.exe –File C:\PS\Test1.ps1
–ComputerName INDY-DC1
The original goal was to simplify this so the user did not
have to type in PowerShell. At this
point, I would actually have the user use PowerShell and turn this script into
a cmdlet in an auto-loading module. To
do this new process via batch file, here are the steps:
1.
Open Notepad
2.
Open the batch file in notepad
3.
Manually enter the computer name.
4.
Save the file
5.
Double click the desk shortcut to the batch
file.
If this was a cmdlet in an auto-loading module, here is the
process:
1.
Open PowerShell
2.
Type CmdletName
–ComputerName INDY-DC1
That is it!
Comments