Formatting of Output and expanding variables

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 8 months ago.

  • Author
  • #5066

    by surge3333 at 2012-08-31 11:37:58

    I’m trying to run a little script which reads an input file and formats copy statements into a batch file that will be executed later. I’m having issues getting the formatting as I need it, and the closest I’ve come is the following, which doesn’t expand the variable I need in the copy statement –

    foreach ($Money in (gc "E:\MoneyShot.txt")) {Write-Output ' "XCOPY /e /i /q /s "\\Server1\f$\Program Files\Somewhere\$Money" "\\Server2\e$\SomewhereElse\$Money" ' | Out-File "E:\Test.bat" -append}

    Creates this for me –

    "XCOPY /e /i /q /s "\\Server1\f$\Program Files\Somewhere\$Money" "\\Server2\e$\SomewhereElse\$Money"

    Any idea how I can get this formatting to work such that the $Money variable is expanded here?


    by DonJ at 2012-08-31 11:44:20

    So, the f$ may well be confusing it. Try using f`$ (which will escape that $).

    But the big problem is that your string is delimited in single quotes. Variable replacement only happens inside double quotes. It's the outermost set of quotes that determine this; the fact that you're using double quotes internally doesn't matter. If you NEED to use double quotes, do this:

    Write-Output " `"XCOPY /e /i /q /s `"\\Server1\f`$\Program Files\Somewhere\$Money`" `"\\Server2\e`$\SomewhereElse\$Money`" "

    I'm using double quotes as the outermost set, and then escaping the internal ones so they'll be seen as literals, not as string delimiters.

    by mjolinor at 2012-08-31 12:40:22

    Another option is to use an expandable here-string:
    [script=powershell]$Money = 'ThisIsMoney'

    $text = @"
    "XCOPY /e /i /q /s "\\Server1\f$\Program Files\Somewhere\$Money" "\\Server2\e$\SomewhereElse\$Money"


    Inside the here-string, variables and sub-expressions will be expanded but normal quoting rules do not apply. You can put whatever kind of quotes you want, wherever you want them – even out of balance quotes (hint).

    by DonJ at 2012-08-31 12:50:13

    Ah, yes, the here-string! So, surge3333, the trick there is again to have the double quotes be the outermost set. Within a here-string, any other double quotes are automatically treated as literals, so they won't "close" the string. The here-string is closed by the final "@, which must start on a newline as mjolinor has done. Great option.

You must be logged in to reply to this topic.