Calling Native Commands Safely

by Oct 16, 2012

Sometimes it isn’t easy to call a command-line tool with some arguments. The PowerShell parser may interfere, and your call may even return completely wrong information.

For example, run this command both in a cmd.exe shell and in PowerShell:

findstr /s /i 'New-Object' *.ps1 c:\windows

It is supposed to list all PowerShell scripts in c:\windows or a subfolder that contains the word “New-Object”. Compare the results. They are different!

One common workaround is to explicitly run those commands in a cmd.exe shell like this:

cmd.exe /c findstr /s /i 'New-Object' *.ps1 c:\windows

As it turns out, this won’t help either. The result is still different. With PowerShell v3, you can finally make sure that your arguments reach the console tool untouched by the parser. Use the new parameter –%:

cmd.exe --% /c findstr /s /i 'New-Object' *.ps1 c:\windows

Twitter This Tip! ReTweet this Tip!