Friday, July 04, 2008

Constructing commands/command line - a PowerShell hint

I was just trying to compose a correct robocopy command in my script - and instead of having robocopy to give me an error, I would like to see the command before attempting to test the command. Naturally, I could built up the command in a string and echo/execute that, but when it can be done easier (we are talking a 5 line script here) it should.

I have something like this

robocopy $from "$(split-path -parent $myinvocation.mycommand.definition)"\subpath /mir



Now, if I want to see what that resolves to, I normally would surround it with quotes, echoing it out. But when you do that, you have to take the existing quotes into account and start duplicating or escaping them. Not so great. And using single quotes is not an option as that will turn off variable substitution. Luckily, PowerShell has the here-double quote operator: @" "@. This multi-line quoting operator does not require quotes in the content to be doubled.



So to see the command, surround it with @" on the line above and place "@ on the line below. Remember that "@ must start in column 1 of the line to end the string.




@"
robocopy $from "
$(split-path -parent $myinvocation.mycommand.definition)"\subpath /mir
"
@



 



You should also remember that PowerShell has the here-single quote operator @' and '@. In this case, variable substitution is not performed.

No comments: