There are several 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 can omit the path but must instead explicitly indicate the current directory using .\ (or ./ will also work)
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
An alternative which allows running a script (or command) on local or remote computers is Invoke-Command
PS C:\> invoke-command -filepath c:\scripts\test.ps1 -computerName Server64
1unless they are explicitly defined as globals: Function SCOPE:GLOBAL or Filter SCOPE:GLOBAL or Set-Variable -scope "Global"
See the PowerShell elevation page for ways of running a script or a PowerShell session "As admin"
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"
Run a batch script from PowerShell:
PS C:\> ./demo.cmd
Early versions of PowerShell would only run internal CMD commands if the batch file was run by explicitly calling the CMD.exe shell and passing the batch file name.
This will run the CMD.exe version of DIR rather than the powershell DIR alias for Get-ChildItem:
PS C:\> CMD.exe /C dir
Run a vb script from PowerShell:
PS C:\> cscript c:\batch\demo.vbs
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:
- Currently defined aliases
- Currently defined functions
- Commands located in the system path.
#Yeah, I'm gonna run to you, cause when the feelin's right I'm gonna stay all night, I'm gonna run to you# ~ Bryan Adams
Invoke-Command - Run commands on local and remote computers.
Invoke-Expression - Run a PowerShell expression.
Invoke-Item - Invoke an executable or open a file (START)
The call operator (&) - Execute a command, script or function
Set-Variable - Set a variable and its value
Functions - Write a named block of code
CMD Shell: Run a script from the CMD shell
VBScript: Run a script from VBScript