Calling a PowerShell script from command line with parameters

Whether you need to setup a scheduled task or set up a build event in TFS, you most likely will need to know how to call a PowerShell script via the command prompt with parameters. The syntax is pretty easy, but if you miss a switch or two, it can have you scratching your head for a few minutes.

Your first step is to create the example PowerShell script so we can call it from the command prompt.

Param(
 [string]$FirstName,
 [string]$LastName
)
"Hello '$FirstName' and '$LastName'"

The Param keyword will tell the PowerShell script to accept these parameters. More information can be found here. Go ahead and save the code to a script so you can call via the command line.

Now comes the command line call. I’m going to give you the full call, then identify the pieces afterwards.

Powershell.exe -ExecutionPolicy Bypass -File "[PathToFile]\[FileName].ps1" -FirstName "Jacob" -LastName "Saylor"
  • Powershell.exe – This tells the command prompt to execute the following with PowerShell. If you get an error similar to ‘Powershell.exe’ is not recognized as an internal or external command, operable program or batch file. make sure you have PowerShell in your system path. You can specify the PowerShell executable path, but if your calling PowerShell on a regular basis, you are going to want to add this to your path.
  • -ExecutionPolicy Bypass – This tells PowerShell to run the script even though the script is not signed.
  • -File “[PathToFile]\[FileName].ps1” – This is the script you would like to run. If your path has spaces in it, you will need to surround it with quotes.
  • -FirstName “Jacob” -LastName “Saylor” – These are your parameters. You can omit the -ParameterName, but I would advise against it in case you change the order of parameters, add any additional ones, remove any, etc…

That’s all there is to it!

Jacob Saylor

Software developer in Kentucky

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: