When you launch a PowerShell script externally – as a scheduled task, or via shortcut, for example – you probably know that you cannot run the script as-is. The file extension ".ps1" is not associated with powershell.exe. So many people launch scripts this way:
|PS> powershell.exe –File c:\somepath\myscript.ps1|
Always Exclude Profiles: -NoProfile!
This can be dangerous and inefficient, because PowerShell will load all profile scripts that may exist, and only then will it load your script and execute it.
Profile scripts – when present – behave like "autoexec.bat" for the console: they start automatically whenever PowerShell starts. With profile scripts, users can customize "their" PowerShell environment, and for example load commands, change colors, and check the corporate cafeteria menu.
The variable $profile will list the path names for all supported profile scripts:
Find out the potential profile paths – profile files are optional
When you want to launch a production script, you neither want all of this to happen nor would you want your script to depend on anything defined in one of the profile scripts.
By using -NoProfile, you ask PowerShell to not execute profile scripts and instead right away launch your script in an untouched environment:
|PS> powershell.exe –NoProfile –File c:\somepath\myscript.ps1|
Other Useful Options
Powershell.exe has a number of additional options, and some are also useful for launching scripts.
For example, if you cannot be sure whether script execution was enabled at all, you should make sure that you allow it explicitly:
|PS> powershell.exe –NoProfile –ExecutionPolicy Bypass –File c:\somepath\myscript.ps1|
This is how production scripts should be launched safely
To get a list of all options, open a PowerShell console, and then enter this command:
|PS> powershell.exe /?
PowerShell[.exe] [–PSConsoleFile <file> | –Version <version>]
PowerShell[.exe] –Help | –? | /?
If the value of Command is "–", the command text is read from standard
If the value of Command is a script block, the script block must be enclosed
If the value of Command is a string, Command must be the last parameter
To write a string that runs a Windows PowerShell command, use the format:
–Help, –?, /?
# To use the –EncodedCommand parameter:
Listing all parameters supported by powershell.exe
So, if you wanted to launch a PowerShell Version 2.0 to test backwards compatibility of your scripts, simply use -Version 2.0. A PowerShell console will start and indeed display a copyright of 2009.