Contact

Subscribe via Email

Subscribe via RSS/JSON

Categories

Creative Commons Attribution 4.0 International License
© Rakhesh Sasidharan

Elsewhere

PowerShell.exe command line switches

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:

You can run a PowerShell cmdlet (or scriptblock) via the -command parameter. Couple of things to remember:

  1. 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.
  2. From within a PowerShell window: The argument to -command can be a cmdlet or a script block. Both work.
  3. From within a PowerShell window, if you launch powershell.exe via start-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 to powershell.exe. Something like this:

    The -noexit switch must be placed before the -command parameter else it has no effect.

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

PowerShell.exe command line switches by rakhesh is licensed under a Creative Commons Attribution 4.0 International License.