O'Reilly logo

Windows PowerShell Quick Reference by Lee Holmes

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Writing Scripts, Reusing Functionality

When you want to start packaging and reusing your commands, the best place to put them is in scripts and functions. A script is a text file that contains a sequence of PowerShell commands. A function is also a sequence of PowerShell commands but is usually used within a script to break it into smaller, more easily understood segments.

Writing Scripts

To write a script, write your PowerShell commands in a text editor and save the file with a .PS1 extension.

Running Scripts

There are two ways to execute a script: by invoking it or by dot-sourcing it.

Invoking

Invoking a script runs the commands inside it. Unless explicitly defined with the GLOBAL scope keyword, variables and functions defined in the script do not persist once the script exits.

You invoke a script by using the invoke/call operator (&) with the script name as the parameter:

& "C:\Script Directory\Run-Commands.ps1" <Parameter List>

You can use either a fully qualified path or a path relative to the current location. If the script is in the current directory, you must explicitly say so:

.\Run-Commands.ps1 <Parameter List>

If the path contains no spaces, you may omit both the quotes and invoke operator.

Dot-sourcing

Dot-sourcing a script runs the commands inside it. Unlike invoking a script, variables and functions defined in the script do persist after the script exits.

You invoke a script by using the dot operator (.) with the script name as the parameter:

. "C:\Script Directory\Run-Commands.ps1" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required