Home Best Practice Scripts Always Use -NoProfile To Launch Scripts
 

Always Use -NoProfile To Launch Scripts

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:

PS> $profile
C:\Users\Tobias\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

PS> $profile.CurrentUserCurrentHost
C:\Users\Tobias\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

PS> $profile.CurrentUserAllHosts
C:\Users\Tobias\Documents\WindowsPowerShell\profile.ps1

PS> $profile.AllUsersCurrentHost
C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShellISE_profile.ps1

PS> $profile.AllUsersAllHosts
C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1

  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>]
    [–NoLogo] [–NoExit] [–Sta] [–Mta] [–NoProfile] [–NonInteractive]
    [–InputFormat {Text | XML}] [–OutputFormat {Text | XML}]
    [–WindowStyle <style>] [–EncodedCommand <Base64EncodedCommand>]
    [–File <filePath> <args>] [–ExecutionPolicy <ExecutionPolicy>]
    [–Command { – | <script–block> [–args <arg–array>]
                  | <string> [<CommandParameters>] } ]

PowerShell[.exe] –Help | –? | /?

–PSConsoleFile
    Loads the specified Windows PowerShell console file. To create a console
    file, use Export–Console in Windows PowerShell.

–Version
    Starts the specified version of Windows PowerShell.
    Enter a version number with the parameter, such as "–version 2.0".

–NoLogo
    Hides the copyright banner at startup.

–NoExit
    Does not exit after running startup commands.

–Sta
    Starts the shell using a single–threaded apartment.
    Single–threaded apartment (STA) is the default.

–Mta
    Start the shell using a multithreaded apartment.

–NoProfile
    Does not load the Windows PowerShell profile.

–NonInteractive
    Does not present an interactive prompt to the user.

–InputFormat
    Describes the format of data sent to Windows PowerShell. Valid values are
    "Text" (text strings) or "XML" (serialized CLIXML format).

–OutputFormat
    Determines how output from Windows PowerShell is formatted. Valid values
    are "Text" (text strings) or "XML" (serialized CLIXML format).

–WindowStyle
    Sets the window style to Normal, Minimized, Maximized or Hidden.

–EncodedCommand
    Accepts a base–64–encoded string version of a command. Use this parameter
    to submit commands to Windows PowerShell that require complex quotation
    marks or curly braces.
   
–File
    Runs the specified script in the local scope ("dot–sourced"), so that the
    functions and variables that the script creates are available in the
    current session. Enter the script file path and any parameters.
    File must be the last parameter in the command, because all characters
    typed after the File parameter name are interpreted
    as the script file path followed by the script parameters.

–ExecutionPolicy
    Sets the default execution policy for the current session and saves it
    in the $env:PSExecutionPolicyPreference environment variable.
    This parameter does not change the Windows PowerShell execution policy
    that is set in the registry.

–Command
    Executes the specified commands (and any parameters) as though they were
    typed at the Windows PowerShell command prompt, and then exits, unless
    NoExit is specified. The value of Command can be "–", a string. or a
    script block.

    If the value of Command is "–", the command text is read from standard
    input.

    If the value of Command is a script block, the script block must be enclosed
    in braces ({}). You can specify a script block only when running PowerShell.exe
    in Windows PowerShell. The results of the script block are returned to the
    parent shell as deserialized XML objects, not live objects.

    If the value of Command is a string, Command must be the last parameter
    in the command , because any characters typed after the command are
    interpreted as the command arguments.

    To write a string that runs a Windows PowerShell command, use the format:
  "& {<command>}"
    where the quotation marks indicate a string and the invoke operator (&)
    causes the command to be executed.

–Help, –?, /?
    Shows this message. If you are typing a PowerShell.exe command in Windows
    PowerShell, prepend the command parameters with a hyphen (–), not a forward
    slash (/). You can use either a hyphen or forward slash in Cmd.exe.

EXAMPLES
    PowerShell –PSConsoleFile SqlSnapIn.Psc1
    PowerShell –version 2.0 –NoLogo –InputFormat text –OutputFormat XML
    PowerShell –Command {Get–EventLog –LogName security}
    PowerShell –Command "& {Get–EventLog –LogName security}"

    # To use the –EncodedCommand parameter:
    $command = 'dir "c:\program files" '
    $bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
    $encodedCommand = [Convert]::ToBase64String($bytes)
    powershell.exe –encodedCommand $encodedCommand

PS> 

  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.