Friday, November 6, 2015

Working with double quotes in PowerShell

If you have worked with PowerShell for any length of time, you will soon realize that escaping double quote characters is troublesome task because double quotes is not only used to define strings but is also used to expand variables inside of strings!

Needless, to say, at some time or another, you will need to escape double quotes in your strings (particularly when working with paths used for command-line tools).

Fortunately, TechNet has an excellent article on managing double quotes in your PowerShell scripts:

Though it is definitely the most easily readable for single line text, here-strings are definitely the easiest technique to use:

The reason that Here-Strings are not the most readable is because Here-strings require the @" to begin a line and then the text on a separate line and finally the "@ on a 3rd line!  Therefore, a single line of text, suddenly needs to be stretched across 3 lines in your PowerShell script!

A situation in which I needed to use Here-Strings was when I was using the command-line tool RoboCopy:

$RoboCopyArgs = @"
"$SrcFileDirectory" "$DestDirectory" /MIR /FFT /Z /XA:H /W:5
Write-Host "These are the RoboCopy Args:"
Write-Host $RoboCopyArgs
Start-Process $RoboCopy -Verb runAs $RoboCopyArgs

No comments:

Post a Comment