Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active February 17, 2023 09:40
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save magnetikonline/f880b0cb063c54568ade7073f935bbd1 to your computer and use it in GitHub Desktop.
Save magnetikonline/f880b0cb063c54568ade7073f935bbd1 to your computer and use it in GitHub Desktop.
PowerShell execute command (.exe) with arguments safely (e.g. with spaces).

PowerShell execute command with arguments safely

In my opinion this is the best way for executing external commands from PowerShell with arguments in a safe manner - via the use of an array to hold the arguments.

Consider this one a PowerShell gem to keep in the toolbox.

Note: the example below makes use of EchoArgs.exe - a small utility that simply echoes back arguments passed to it. Utility is part of the PowerShell Community Extensions, or the exe alone can be downloaded at http://ss64.com/ps/EchoArgs.exe.

Example

Running example.ps1 yields the following output:

.\example.ps1
Arg 0 is <-switch>
Arg 1 is <-key1>
Arg 2 is <value>
Arg 3 is <-key2>
Arg 4 is <value with spaces>
Arg 5 is </D>
Arg 6 is </S>
Arg 7 is <another argument with spaces>

Note that arguments with spaces are correctly passed to EchoArgs.exe without the need for quoting or escaping.

Second call to EchoArgs.exe will pipe all output to output.txt.

Reference

Set-StrictMode -Version Latest
$cmdPath = "$PSScriptRoot\EchoArgs.exe"
$cmdArgList = @(
"-switch",
"-key1","value",
"-key2","value with spaces"
"/D","/S"
"another argument with spaces"
)
& $cmdPath $cmdArgList
& $cmdPath $cmdArgList >"$PSScriptRoot\output.txt"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment