Powershell

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

Syntax
      powershell[.exe] [-File FilePath Args] [-NoProfile]
         [-Command { - | script-block [-args arg-array] | string [CommandParameters] } ]
            [-PSConsoleFile file | -Version version] [-NoExit] [-Sta] [-Mta]
               [-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
                  [-NoLogo] [-WindowStyle Style] [-NonInteractive]
                     [EncodedCommand Base64EncodedCommand] [-ExecutionPolicy ExecutionPolicy]
                     
      powershell[.exe] -Help | -? | /?

Key
   -File             Execute a script file. The filename is required.
                     If the file/pathname contains spaces then surround with double quotation marks:
                       -file "path to\your script.ps1"

   -Command          Execute commands or a script file of commands 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 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 parenthesis }.
                     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}"

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

   -ExecutionPolicy  Set the default execution policy for the session.

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

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 PowerShell.exe:

::LAUNCHER.CMD
@Echo off
Cls
Pushd %~dp0
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -windowstyle Hidden ./your-script.ps1
Popd

This assumes that your-script.ps1 is in the same folder as the batch file.
If you want to see output/errors from the script omit the -windowstyle Hidden
The Pushd and Popd commands ensure that it works even if run directly from a UNC path.

64 bit vs 32 bit

By default, running PowerShell will launch a 64 bit process C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

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

However if you run a 32 bit shell (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 run the 64 bit version (which is supported by syswow64) from a 32 bit process, 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 \"
The \ is an escape character that is required due to PowerShell's (current) use of CommandLineToArgvW when parsing input arguments.

powershell.exe -Command Start-Process PowerShell -ArgumentList '-NoProfile -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"""

Encoded command

The -EncodedCommand parameter for powershell.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:

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

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
PWRSH - Launch PowerShell core.
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