The powershell.exe
command has many useful switches.
Two especially useful ones are the -Version
and -ExecutionPolicy
switches. The former lets you start PowerShell as a different version – useful you want to test your script on older versions of PowerShell – and the latter lets you set the execution policy for the current session – useful when you are telling users to run a script via the -File
switch and want to allow execution for that session so they don’t get any prompts. This is equivalent to running the following cmdlet from within PowerShell:
1 |
Set-ExecutionPolicy -Scope process <ExecutionPolicy> |
You can run a PowerShell cmdlet (or scriptblock) via the -command
parameter. Couple of things to remember:
- From within a command prompt window: If the argument to
-command
is a cmdlet it is executed and the result passed to command prompt. But if the argument is a script block then it is only typed as it is, no execution happens. - From within a PowerShell window: The argument to
-command
can be a cmdlet or a script block. Both work. - From within a PowerShell window, if you launch
powershell.exe
viastart-process
same rules as the command prompt window case apply. Also, bear in mind as a new process is started it terminates immediately after the cmdlet/ script block is executed. If you want the window to not exit, specify the-noexit
switch as an argument topowershell.exe
. Something like this:1PS> Start-Process powershell -ArgumentList "-noexit -command get-date"The
-noexit
switch must be placed before the-command
parameter else it has no effect. - In all cases, when a script block is passed to
-command
if it is enclosed in double quotes (as a string) and the script block is prefixed with the&
operator (the call operator) the script block will get executed. Like thus:1C:\> powershell -command "& { get-date }"