Before running any scripts on a new powershell installation, you must first set an appropriate Execution Policy, e.g. Set-ExecutionPolicy RemoteSigned
A PowerShell script is the equivalent of a Windows CMD or MS-DOS batch file, the file should be saved with a .ps1 extension, e.g. MyScript.ps1
The most common way to run a script is by invoking it:
& "C:\Belfry\My first Script.ps1"
If the path does not contain any spaces, then you can omit the quotes and the '&' operator
C:\Belfry\Myscript.ps1
If the script is in the current directory, you must indicate this using .\
.\Myscript.ps1
When you invoke a script using the syntax above, variables and functions defined in the script will disappear when the script ends.1
Dot Sourcing
Run a script by dot-sourcing it:
. "C:\Belfry\My first Script.ps1"
Dot-sourcing a script in the current directory:
. .\Myscript.ps1"
When you dot source a script, all variables and functions defined in the script will persist even when the script ends.
The System Path
If you run a script (or even just enter a command) without specifying the fully qualified path name, PowerShell will search for it as follows:
Firstly it will look at currently defined aliases, then currently defined functions and lastly commands located in the system path.
1unless they are explicitly defined as globals: Function SCOPE:GLOBAL or Filter SCOPE:GLOBAL or Set-Variable -scope "Global"
# Yeah - I'm gonna run to you, cause when the feelins right I'm gonna stay all night, I'm gonna run to you# - Bryan Adams
Related:
Set-Variable - Set a variable and its value
Functions - Write a named block of code
Return statement
Exit Statement