How to Run a PowerShell Script from the Command Line

PowerShell is a powerful scripting language and shell developed by Microsoft to help IT professionals and developers automate tasks and processes in Windows. One of the main benefits of PowerShell is the ability to create reusable scripts that can automate repetitive tasks.

But how do you run those PowerShell scripts? In this comprehensive guide, we’ll cover everything you need to know to successfully run PowerShell scripts from the command line in Windows.

Prerequisites for Running PowerShell Scripts

Before diving into the details of running scripts, let’s quickly cover what you’ll need:

  • PowerShell Installed – PowerShell comes installed by default in every Windows version starting with Windows 7/Windows Server 2008 R2. So as long as you’re on a supported Windows OS, you likely already have PowerShell.
  • Execution Policy Set – The execution policy determines whether scripts are allowed to run. It’s likely already set, but double-check to be sure.
  • Text Editor – To create scripts, you’ll need a basic text editor like Notepad. Popular third-party choices include Visual Studio Code, Atom, Sublime Text, and Notepad++.
  • PowerShell Script file – This is the PS1 file that contains your PowerShell code and script logic. All PowerShell scripts end with the .ps1 file extension.

As long as those prerequisites are met, you can now run PowerShell scripts! Next let’s look at the different options available.

Methods for Running PowerShell Script Files

There are a few different options for running PowerShell script files from the command line:

  • Invoke Directly by Path – Call the script directly by pointing to the file path
  • Dot Sourcing – Execute script contents in current shell’s scope
  • Job Command – Run script asynchronously as background job
  • Invoke Operator – Flexible script execution with parameters, output control, etc.

The best option will depend on your specific needs and script requirements. Let’s explore each method.

Invoke PowerShell Scripts by File Path

The most straightforward way to run a PowerShell script is by calling the script file directly using its full file system path:

```powershell
PS C:\Users\John> C:\Scripts\start-process.ps1
```
  • Specify the full file path pointing to the script after the prompt
  • PowerShell will execute the code within the specified PS1 script
  • Any output will be printed to the host shell executing the command

Key Points

  • Simple and direct script execution
  • The only option if execution policy restrictions are enabled
  • Entire script executes in current shell’s scope

This is a great option if you want simple, direct execution without any special handling. However, it doesn’t offer flexibility to control parameters or output.

Next, let’s look at dot sourcing.

Dot Sourcing PowerShell Scripts

Dot sourcing enables you to execute script contents within the current shell scope rather than spawning a child scope:

```powershell 
PS C:\Users\John> . C:\Scripts\start-process.ps1 
```
  • Insert a dot and space . before the file path
  • Script contents execute in the current shell scope
  • Any functions/variables will persist in session after running

Key Points

  • Executes in current shell scope rather than child scope
  • Functions, aliases, variables persist after script finishes
  • Output directly printed rather than returnable

Dot sourcing is extremely useful for things like integrating functions, initializing settings, and setting up the environment. The tradeoff is that it lacks options for parameterization or output control.

Up next we’ll look at running scripts as background jobs.

Running PowerShell Scripts as Jobs

You can use the Start-Job cmdlet to execute scripts asynchronously as a PowerShell job:

```powershell
PS C:\Users\John> Start-Job -FilePath C:\Scripts\start-process.ps1
```
  • Use Start-Job and specify script with -FilePath parameter
  • Creates a PowerShell job object and runs script in the background
  • Script output is stored in job object rather than displayed

Key Points

  • Enables asynchronous and parallel script execution
  • Output is captured rather than directly displayed
  • Use Get-Job and Receive-Job cmdlets to retrieve output

Jobs are fantastic any time you need to execute processes asynchronously or in parallel. The main limitation is tedious output retrieval.

Finally, let’s explore theinvoke operator which offers expanded execution control.

Invoke Operator for PowerShell Script Execution

The & invoke operator provides the most flexible way to call scripts with added execution control:

```powershell
PS C:\Users\John> & C:\Scripts\start-process.ps1 -Verbose 
```
  • Include the & before the script path
  • Supports parameter binding for passing arguments
  • Output can be suppressed, captured, redirected, etc.

Key Points

  • Parameter binding for passing arguments to scripts
  • Fine tuned control over execution and output
  • Typically the best option for reusable script components

We’ve now covered the primary methods for running PowerShell scripts from the command line. But there are additional best practices worth noting as well.

Additional PowerShell Script Execution Tips

Here are some other great tips for running PowerShell scripts from the command line:

  • Check the execution policy – Use Get-ExecutionPolicy to verify the policy is not blocking scripts.
  • Use full paths – Always use full absolute paths rather than relative to avoid issues.
  • Leverage parameters – Take advantage of parameter binding to increase reusability.
  • Handle output – Suppress, capture or redirect output depending on need.
  • Consider security – Validate script trustworthiness and sanitize any inputs.
  • Debug issues – For syntax errors, missing cmdlets, etc. test scripts in the shell first.

Also keep in mind that the same PowerShell syntax works for running scripts in the ISE or third-party tools like VSCode. The only difference is specifying a file path since they have direct editor integration.

With those pro tips covered, let’s now run through a hands-on script execution example.

Hands-on Example: Running a PowerShell Script

Let’s walk through executing a sample PowerShell script to see the invoke operator in action:

  1. Create Sample Script – Make a script called get-process-details.ps1 using a text editor.
  2. Add Code – Put the following code in the new PS1 file:Param( [string]$ProcessName ) Get-Process -Name $ProcessName | Select-Object NPM, CPU, Id
  3. Open Shell – Launch a PowerShell session either in the ISE or command prompt.
  4. Execute Script – Run the script while passing a process name argument:PS C:\Scripts> & .\get-process-details.ps1 -ProcessName explorer
  5. See Output – Details on the explorer.exe process will print showing the script executed:NPM(K) CPU(s) Id ------ ------ -- 23 3 2140

And with just a few lines of code we have a reusable PowerShell script extracting process data leveraging parameter binding and output printing!

Summary

In this guide you learned multiple methods for running PowerShell script files from the command line, including:

  • Directly invoking by file path
  • Dot sourcing into current session
  • Asynchronously via background jobs
  • Flexible invocation using the & operator

You also picked up some additional best practices and saw hands-on examples applying these techniques.

Now you have all the knowledge needed to effectively run PowerShell scripts from the command line like a pro! Automate all the things!

Leave a Comment