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 in the local scope ("dot-sourced"), so that the functions and variables
                     that the script creates are available in the current session. The filename is required.
                     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
                     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.

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

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

   -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', 'Minimized', 'Maximized' 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.

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

Set the target as:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
and pass the option C:\path to\your-script.ps1

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

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

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

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

powershell.exe  ^
   $userprofiles = @('C:\Users\');  ^
   foreach ($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 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"

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

PowerShell.exe -file "C:\demo\MyScript.ps1"
or more concisely:
PowerShell.exe 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 Cmdlets

List of all PowerShell cmdlets
powershell_ise.exe - Launch PowerShell ISE (alias ise)
pwsh - Launch PowerShell core. (PowerShell core can be run side-by-side with Windows PowerShell.exe).
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 SS64.com
Some rights reserved