Launch a PowerShell session and/or run a PowerShell script.

      pwsh[.exe] [-Login] [[-File] FilePath Args] [-NoProfile] [-NoProfileLoadTime]
         [-Command { - | script-block [-args arg-array]
                       | string [CommandParameters] } ]
           [[-CommandWithArgs string] [CommandParameters]] [-ConfigurationFile FilePath]
              [-ConfigurationName string] [-CustomPipeName string] [-EncodedCommand Base64EncodedCommand]
                 [-ExecutionPolicy ExecutionPolicy] [-InputFormat {Text | XML}] [-Interactive] [-MTA]
                    [-NoExit] [-NoLogo] [-NonInteractive] [-OutputFormat {Text | XML}]
                       [-SettingsFile FilePath] [-SSHServerMode] [-STA]
                          [-Version] [-WindowStyle style] [-WorkingDirectory directoryPath]

      pwsh[.exe] -h | -Help | -? | /?

   -f               Execute a script file in the local scope ("dot-sourced"), so that the functions and variables
                    that the script creates are available in the current session. The FilePath is required.

                    If the value of File is -, the command text is read from standard input.
                    Running pwsh -File - without redirected standard input starts a regular session.
                    This is the same as not specifying the File parameter at all.

                    If the file/pathname contains spaces then surround with double quotation marks:
                       -file "path to\your script.ps1"
                     -File must be the last parameter in the command, because all characters typed after -File
                    will be interpreted as the script file path followed by the script parameters.

                    Unless -NoExit is specified (-NoExit -file ..) then any local functions/variables will be discarded
                    when the script ends and the scope is closed.

   -Command         Execute commands or a script file of commands as though they
   -c               were typed at the PowerShell prompt, and then exit, unless -NoExit is specified.

                     The value of Command can be "-", a string. or a script block.
                     If 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
                     with { curly parentheses }.
                     Specify a script block only when running PowerShell.exe from PowerShell.

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

                     To write a string that runs a PowerShell command, use the format:  "& {command}"
                     where the quotation marks indicate a string and the invoke operator (&) executes the command.

   -CommandWithArgs  This is an experimental feature added in 7.4.
   -cwa              Executes a PowerShell command with arguments.
                     Unlike -Command, this parameter populates the $args built-in variable that can be used by the
                     command. The first string is the command. Additional strings delimited by whitespace are the arguments.

   -config           Specifies a configuration endpoint in which PowerShell is run.
                     This can be any endpoint registered on the local machine including the default PowerShell remoting
                     endpoints or a custom endpoint having specific user role capabilities.

   -ConfigurationFile Specifies a session configuration (.pssc) file path.
                     The configuration contained in the configuration file will be applied to the PowerShell session.

   -CustomPipeName   Specifies the name to use for an additional IPC server (named pipe) used for debugging and
                     other cross-process communication.
                     This offers a predictable mechanism for connecting to other PowerShell instances.
                     Typically used with the CustomPipeName parameter on Enter-PSHostProcess.
                     This parameter was introduced in PowerShell 6.2.

   -EncodedCommand   Accepts a Base64-encoded string version of a command.
   -e                Use this parameter to submit commands to PowerShell that require complex, nested quoting.
   -ec               The Base64 representation must be a UTF-16LE encoded string.

   -ExecutionPolicy  Set the default execution policy for the current session and save it in
   -ex               the $env:PSExecutionPolicyPreference environment variable.
   -ep               This parameter does not change the persistently configured execution policies.
                     This parameter only applies to Windows computers.
                     On non-Windows platforms, the parameter and the value provided are ignored.

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

   -Interactive      Present an interactive prompt to the user. Inverse for NonInteractive parameter.

   -Login            On Linux and macOS, starts PowerShell as a login shell, using /bin/sh to
   -l                execute login profiles such as /etc/profile and ~/.profile.
                     On Windows, this switch does nothing.
                     This parameter must come first to start PowerShell as a login shell.
                     This parameter is ignored if it is passed in another position.

   -MTA              Start PowerShell using a multi-threaded apartment.
                     This switch is only available on Windows.
                     Using this parameter on non-Windows platforms results in an error.

   -NoExit           Do not exit after running startup commands.

   -NoLogo           Hide the copyright banner at startup.

   -NonInteractive   Create a session that shouldn’t require user input.
   -noni             This is useful for scripts that run in scheduled tasks or CI/CD pipelines.
                     Any attempts to use interactive features, like Read-Host or confirmation prompts,
                     result in statement terminating errors rather than hanging.

   -NoProfile        Do not load the PowerShell profile. No pre-defined functions will be available.
                     When setting up a scheduled job, using -NoProfile can be a quick way
                     to document the fact that nothing special in the profile is needed.
                     It also ensures that any future profile changes will not affect the job.

   -NoProfileLoadTime Hide the PowerShell profile load time text shown at startup when the
                     load time exceeds 500 milliseconds.

   -OutputFormat     Format the output.
   -o                Valid values are "Text" (text strings) or "XML" (serialized CLIXML format).
   -of               Example: pwsh -o XML -c Get-Date
                     When called within a PowerShell session, you get deserialized objects as output
                     rather plain strings.
                     When called from other shells, the output is string data formatted as CLIXML text.

   -SettingsFile     Override the system-wide PowerShell.config.json settings file for the session.
   -settings         By default, system-wide settings are read from the powershell.config.json in the
                     $PSHOME directory. Note that these settings aren’t used by the endpoint specified
                     by the -ConfigurationName argument.

   -SSHServerMode    Used in sshd_config for running PowerShell as an SSH subsystem.
   -sshs             It isn’t intended or supported for any other use.

   -Sta              Start the shell using a Single-Threaded Apartment. This is the default.
                     This switch is only available on the Windows platform.
                     Using this parameter on non-Windows platforms results in an error.

   -Version          Start the specified version of Windows PowerShell.

   -WindowStyle      Set the window style to 'Normal', 'Minimized', 'Maximized' or 'Hidden'.

   -Help, -?, /?     Display Help

Standard Aliases for Powershell_ISE.exe: ise

When launching a .ps1 script you may wish to specify -noprofile to make sure that the script runs in a default PowerShell environment and does not load any profile scripts.

Before running any scripts on a new PowerShell installation, you must first set an appropriate Execution Policy

PS C:\> Set-ExecutionPolicy RemoteSigned

In Windows Explorer, you can type "powershell" in the address bar to open a PowerShell prompt at the current location.

From a CMD shell rather than running PowerShell within the command prompt, you might want to open a separate PowerShell window - so use START POWERSHELL.

When running Pwsh.exe -Command script-block you don’t need to add quotes around the script-block.
For example: Pwsh.exe -Command Get-Service wuauserv everything after -Command is passed to PowerShell,
However when calling Pwsh.exe from the CMD.exe shell (a common requirement) you will need to escape some characters which have a special meaning in CMD:

Launch with a Double Click

To create an icon/shortcut which can launch PowerShell and execute a script, you can use a simple batch script which calls Pwsh.exe:

Set the target as:
C:\Program Files\PowerShell\7\pwsh.exe
and pass the option C:\path to\your-script.ps1

Optionally include the option -windowstyle Hidden to supress output/errors from the script.

Run a Script As Admin

To run PowerShell and run a script

pwsh.exe -Command Start-Process Pwsh -ArgumentList '-File C:\demo\MyScript.ps1' -Verb RunAs 

This runs pwsh.exe -Command and then a PowerShell cmdlet
Note this first invocation of PowerShell is not elevated. The cmdlet we run is Start-Process and we use this to run a second copy of Pwsh, this time elevated through the use of the -verb runas option.

The parts in bold above are elevated. Because this is being run under a new elevated session it is important to pass the full path to the script. If you have a long filename with spaces, see the next section below.

The Start-Process options -NoNewWindow and -Verb RunAs cannot be combined as that would elevate the already running session.

For more details see the elevation page which includes a self-elevating PowerShell script.

Long Filenames

If you are calling one PowerShell session from another, this is a non issue, but if you are calling PowerShell from a CMD batch file and the command contains double quotation marks, they must be escaped: " becomes \"
The \ is an escape character that is required due to PowerShell’s use of CommandLineToArgvW to parse input arguments. [x]

pwsh.exe -Command Start-Process Pwsh -ArgumentList '-NoProfile -File \"C:\long name\test one.ps1\"' -Verb RunAs
Extending the above to pass quoted arguments to the script:
pwsh.exe -Command Start-Process Pwsh -ArgumentList '-NoProfile -File \"C:\long name\test two.ps1\" \"Arg1\" \"Arg2\"' -Verb RunAs

Alternatives are to use 'single quote' marks where possible, or to escape using triple quotes """Arg1"""

In addition to escaping quotation marks, you may also need to escape any PowerShell characters which have meaning in the CMD shell,
e.g. replace ) with ^) the caret here is the CMD escape character.

Embedding PowerShell commands in a CMD batch file

For short simple scripts, you can embed several lines of PowerShell, which will all be passed to PowerShell as a single line. The key to this is adding a ^ batch escape at the very end of each line to escape (effectively remove) the line ending characters.

It is also necessary to escape any pipes, so | becomes ^|

pwsh.exe  ^
   $userprofiles = @('C:\Users\'); ^
   ForEach-Object ($user in $userprofiles) { ^
      Set-Location -Path $user;  ^
      Get-ChildItem -Filter '*.log~' ^| Where-Object { ^
      $_.Attributes -band [System.IO.FileAttributes]::Archive } ^

Encoded command

The -EncodedCommand parameter for pwsh.exe, allows passing PowerShell code as a base-64-encoded string.

First place your code into a variable:

$scriptblock = {     
 # place the commands here
 Write-Output 'This is just a demo'

Then encode the variable:

$encoded = [convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($scriptblock))

Now we can launch Powershell.exe and pass the encoded commands:

pwsh.exe -NoProfile -EncodedCommand $encoded

Exit Codes

In PowerShell the exit code is stored in the automatic variable $LASTEXITCODE.

To read exit codes (other than 0 or 1) launch the PowerShell script and return the $LASTEXITCODE in a single line like this:

pwsh.exe -noprofile C:\scripts\script.ps1; exit $LASTEXITCODE


Run a script (non elevated):

Pwsh.exe -Command "C:\demo\MyScript.ps1"

Run a script (non elevated) in the local scope of the PowerShell session:

Pwsh.exe -file "C:\demo\MyScript.ps1"
or more concisely:
Pwsh.exe C:\demo\MyScript.ps1

Load a console and run a Script:

Pwsh.exe -PSConsoleFile "C:\scripting\MyShell.psc1" -Command ". 'MyScript.ps1'"

Run a command to display the security event log:

pwsh.exe -command {Get-Eventlog -logname security}

Or the same thing but calling PowerShell from the CMD shell:

pwsh.exe -command "& {Get-Eventlog -logname security}"

Run a simple calculation and return (supports Long numbers):

pwsh.exe 200000000*2

PS.cmd - a simple batch file to launch Pwsh with slightly less typing:

@echo off
Pwsh.exe %*

“If you want to launch big ships you have to go where the water is deep” ~ Anon

Related PowerShell Cmdlets

List of all PowerShell cmdlets
PowerShell - Launch a PowerShell 5.1 session and/or run a PowerShell script.
powershell_ise.exe - Launch PowerShell ISE (alias ise)
ScriptRunner - Run one or more scripts in sequence.
Convert-PowerShellToBatch - Encode a PowerShell script to base64, this allows it to be run as a batch script you can double click. (Idera).
Equivalent bash command: bash - launch bash shell.

Copyright © 1999-2024
Some rights reserved