Creating PowerShell Scripts

By Xah Lee. Date: . Last updated: .

You can put commonly used commands into a file, save the file, then you can run it as a script.

For example, create a file with the following content.

# test script
get-date

Save this file for example at C:/Users/xah/PowerShell scripts/xx.ps1.

PowerShell File Name Extension

PowerShell file name should end in .ps1

Running script

To run a script, you can cd to the dir and start the script with ./.

# run a script
cd "C:/Users/xah/PowerShell scripts/"
./xx.ps1

The ./ means the current directory. PowerShell requires you to have that to prevent running things found in the current dir by mistake.

Invocation Operator

You can also call a script by its full path.

# call a script  with the Invocation Operator &
& "C:/Users/xah/PowerShell scripts/xx.ps1"

You need the call operator &, because your path is a string. If you don't use the operator, then PowerShell will simply evaluate that string as a expression, and the result is the same string.

Execution Policy Error

If this is your first time running a script, you'll get a error like this:

File C:\Users\xah\PowerShell scripts\xx.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing"
for more details.

This is because PowerShell has a execution policy for security purposes. By default, it does not allow you to run unsigned scripts. To make it run unsigned scripts you created on your machine, Run the following to set a different policy:

# make local script run but require remote script to be signed
Set-ExecutionPolicy RemoteSigned

Adding Path

You can add your scripts dir to Window's environment variable: $PATH, so you don't have to cd to the dir first to call it.

# display your path env var
$env:path.split(";")

# adding a path to the PATH env var. Must use backslash, not slash.
$env:path = $env:path + ";C:\Users\xah\PowerShell scripts\"

The above will add the path for the current session only. For permanent solution, see: PowerShell: View/Set Environment Variables.

PowerShell

How-to

Advanced

Script Examples