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: http://blogs.technet.com/b/heyscriptingguy/archive/2010/07/28/writing-double-quotation-marks-to-a-text-file-using-windows-powershell.aspx

Though it is definitely the most easily readable for single line text, here-strings are definitely the easiest technique to use:  https://technet.microsoft.com/en-us/library/ee692792.aspx

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