Search code examples
powershellpowershell-4.0

How to get powershell to output variable with quotes around it


Despite going over the documentation on single and double quotes using 'about_quoting_rules', I can't seem to get the output I'm looking for.

A little backstory:

I have an excel doc and I'm using powershell to create a foreach over every entry. This, in turn, is being used to generate a robocopy command to kick off a sync job.

The part of my script that's pertinent to this is below:

Foreach($script in $roboSource)
{

    $StandardSwitches = "/copy:DAT /s /dcopy:DAT /V /L"
    $log = "/log:`"$($logPath)$($logFileName)`""                                                                                                #`
    $FileSource = "$($script.a)"
    $FileDestination = "$($script.a)"

    $RoboArgs = "I:\" + $FileSource + " " + "Z:\" + $FileDestination + " " + $StandardSwitches + " " + $log
}

So, right now, $RoboArgs outputs this:

I:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX Z:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX /copy:DAT /s /dcopy:DAT /V /L /log:"C:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX"

What I need $RoboArgs to output is this:

"I:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX" "Z:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX" /copy:DAT /s /dcopy:DAT /V /L /log:"C:\XXXXX\XXXXX\X\XXXXXXX\XXXXX\XXXX"

I've tried adding the backticks to the string, and encapsulating the string and variable together:

$RoboArgs = `""I:\" + $FileSource`"" + " " + "Z:\" + $FileDestination + " " + $StandardSwitches + " " + $log

But regardless of what I try, nothing is resulting in the output that I'm looking for. Any nudge in the right direction would be very helpful and appreciated!


Solution

  • I suggest using PowerShell's string-formatting operator, -f:

    $RoboArgs = '"I:\{0}" "Z:\{1}" {2} {3} {4}' -f 
                  $FileSource, $FileDestination, $StandardSwitches, $log
    
    • Using '...' (single-quoting) as the delimiters allows you to embed " instances as-is.

    • {0} is a placeholder for the 1st RHS operand, {1} for the 2nd, and so on.