Powershell

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

Syntax
      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 | -? | /?
Key
 
   -PSConsole File   Load a PowerShell console file. (created with export-console)

   -Version          Start the specified version of Windows PowerShell.

   -NoLogo           Hide the copyright banner at startup.

   -NoExit           Do not exit after running startup commands.

   -Sta              Start the shell using a single threaded apartment

   -Mta              Start the shell using a multi-threaded apartment

   -NoProfile        Do not load the PowerShell profile. So 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.

   -Noninteractive   Don't present an interactive prompt to the user.

   -InputFormat      Format of data sent to Windows PowerShell. Valid values are
                     "Text" (string) or "XML" (serialized CLIXML format). 

   -OutputFormat     Format the output. Valid values are "Text" (string)
                     or "XML" (serialized CLIXML format).
 

   -Command          Execute commands or a script file of commands 
                     If Command is "-", the command text is read from standard input.

   -WindowStyle      Set the window style to Normal, Minimised, Maximised or Hidden.

   -EncodedCommand   Accepts a base-64 encoded string version of a command, Use this to
                     submit commands to PowerShell that require complex quotation marks
                     or curly braces.

   -File             Execute a script file.
                     Note that '-file' is required if using a pathname that contains any spaces.
                     To be robust and reliable always use  -file "path to\your script.ps1"

   -ExecutionPolicy  Set the default execution policy for the session.

   -Command          Execute the specified commands (and any parameters) as though they
                     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 the value of Command is "-", the command is read from standard input.

                     Script blocks must be enclosed in braces ({}).
                     Specify a script block only when running PowerShell.exe from PowerShell.

                     The results of the script are returned to the parent shell as
                     deserialized XML objects, not live objects.

                     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 call operator (&)
                     causes the command to be executed.

   -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.

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 PowerShell.exe -Command script-block you don't need to add quotes around the script-block.
For example: PowerShell.exe -Command Get-Service wuauserv everything after -Command is passed to PowerShell,
Hhowever when calling Powershell.exe from the CMD.exe shell (a common requirement) you will need to escape some characters which have a special meaning in CMD:

64 bit vs 32 bit

By default, running PowerShell will launch a 64 bit process (C:\Windows\system32\PowerShell.exe)

if you run a 64 bit shell (such as C:\windows\syswow64\cmd.exe) and then launch PowerShell it will launch the 64 bit PowerShell.

However if you run a 32 bit shell (such as C:\windows\syswow64\cmd.exe) and then launch PowerShell, you will launch the 32 bit version of PowerShell (C:\Windows\SysWOW64\WindowsPowerShell\v1.0\PowerShell.exe)

To ensure that you run the 64 bit version (which is supported by syswow64) from CMD, use the sysnative path:
%SystemRoot%\sysnative\WindowsPowerShell\v1.0\powershell.exe

When launching one PowerShell session from another, this script will check the version of PowerShell running and will relaunch itself as 64-bit if you are running in 32-bit.

Run a Script As Admin

To run PowerShell and run a script

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

This runs powershell.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 PowerShell, 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.

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 quotation marks, they must be escaped: " becomes \" This is a CMD escape that works due to PowerShell's (current) use of CommandLineToArgvW, this could change in the future so the safest approach is to avoid long pathnames with spaces.

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

A less readable alternative to backslash escapes is triple quotes """Arg1"""

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:

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

Examples

Run a script (non elevated)

PowerShell.exe -Command C:\demo\MyScript.ps1

Load a console and run a Script:

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

Run a command to display the security event log:

powershell.exe -command {get-eventlog -logname security}

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

powershell.exe -command "& {get-eventlog -logname security}"

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

powershell.exe 200000000*2

PS.cmd - a simple batch file to launch PowerShell with less typing:
@echo off
Powershell.exe %*

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

Related PowerShell Commands:

List of all PowerShell cmdlets
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 © SS64.com 1999-2018
Some rights reserved