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" ...
Get Windows PowerShell Quick Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.