Creating PowerShell Scripts

By Xah Lee. Date:

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 in Notepad with the following content.

# test script

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

The 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/"

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

You can use the slash “/” or backslash “\” for path separators. If your path contain spaces, you'll need to quote whole path as a string.

You can also call a script by its full path.

# call a script by full path, with the Invoke Operator “&”
& "C:/Users/xah/PowerShell scripts/xx.ps1"

You need the invocation 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 execut
ion 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

help about_signing

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

# 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.




Script Examples