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
-commandis 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
-commandcan be a cmdlet or a script block. Both work. - From within a PowerShell window, if you launch
powershell.exeviastart-processsame 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-noexitswitch as an argument topowershell.exe. Something like this:1PS> Start-Process powershell -ArgumentList "-noexit -command get-date"The
-noexitswitch must be placed before the-commandparameter else it has no effect. - In all cases, when a script block is passed to
-commandif 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 }"
