Run a powershell script

There are two ways to run a PowerShell script.

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 (default) way to run a script is by calling it:

PS C:\> & "C:\Belfry\My first Script.ps1"

If the path does not contain any spaces, then you can omit the quotes and the '&' operator

PS C:\> C:\Belfry\Myscript.ps1

If the script is in the current directory, you must indicate this using .\

PS C:\> .\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

When you dot source a script, all variables and functions defined in the script will persist even when the script ends.

Run a script by dot-sourcing it:

PS C:\> . "C:\Belfry\My first Script.ps1"

Dot-sourcing a script in the current directory:

PS C:\> . .\Myscript.ps1"

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:

The call operator (&) - Execute a command, script or function
Set-Variable - Set a variable and its value
Functions - Write a named block of code
Return statement
Exit Statement



Back to the Top

© Copyright SS64.com 1999-2012
Some rights reserved