Update: This still works best for some scenarios, but learn about how to use the call operator to do this and work within the system!
So you want to build up a command line to execute some utility. Simple enough right? Lets use ping as an example. Say you want to ping example.com 5 times. Your parameters would look like http://www.example.com -n 5. Append this to the end of ping in PowerShell and off you go, right?
$pingopts = "www.example.com -n 5" ping $pingopts
Run that in PowerShell and you will hit a small problem. Ping will give you an error saying about not being able to find the host http://www.example.com -n 5.
If you examine the command line that is used to execute ping (pick your favorite tool, I chose process monitor!) what is happening becomes quite clear. The command that was executed was this:
"C:\Windows\system32\PING.EXE" "www.example.com -n 5"
The problem is that the string quotes around $pingopts were kept in place. While keeping quotes is useful when passing paths around it is not what you want in most other circumstances. We need to make those quotes go away and thankfully you can use invoke-expression to do just that.
$pingopts = "www.example.com -n 5" invoke-expression "ping $pingopts"
This code will work perfectly! If you know of any other solutions please post about them, I am sure there are many ways to solve this problem in PowerShell!
In summary: Generally when working with Powershell Cmdlets you don’t have to worry about strings, PowerShell and its cmdlets handle quoting and dequoting them them perfectly, but you have to be careful when interfacing with the non-PowersShell world.
[…] last blog post I did on this topic was about using Invoke-Expression to solve problems with passing parameters to external programs. I resorted to using […]
Pingback by PowerShell Call Operator (&): Using an array of parameters to solve all your quotes problems « Peace For All — September 26, 2011 @ 12:30 pm
[…] last blog post I did on this topic was about using Invoke-Expression to solve problems with passing parameters to external programs. I resorted to using […]
Pingback by PowerShell Call Operator (&): Using an array of parameters to solve all your quoting problems « Peace For All — September 26, 2011 @ 12:31 pm