Escaping variables

Welcome Forums General PowerShell Q&A Escaping variables

This topic contains 2 replies, has 2 voices, and was last updated by

4 years, 5 months ago.

  • Author
  • #23643

    Topics: 16
    Replies: 22
    Points: 2
    Rank: Member
    $var01 = "Something"
    write-host '$var01' #Result is $var01
    write-host "$var01" #Result is Something

    I understand that basic concept.

    I've got a two part question:

    Can you splat variables when using the "&" tool to run .exe files?

    $app = "C:\temp\someapp.exe"
    $varA = 'VarA="C:\Temp\TestPath"' #SingleQuote VarA = DoubleQuote C:\Temp\TestPath DoubleQuote SingleQuote
    $varb = 'VarB="%COMPUTERNAME%"' #SingleQuote VarB = DoubleQuote %COMPUTERNAME% DoubleQuote SingleQuote
    & $app $VarA $VarB

    Second question is:
    What's the syntax to properly produce the following results:

    $varA = 'VarA="C:\Temp\$Var01"'

    to make $varA return (as shown below).


  • #23644

    Topics: 13
    Replies: 4872
    Points: 1,843
    Helping HandTeam Member
    Rank: Community Hero

    I don't understand what you mean by "splat variables." Splatting is the act of feeding a hashtable to a command in order to provide parameter names and values. The way you're using & isn't splatting; it's invocation. And, have you just tried doing it?

    The dollar sign is what cues the variable-replacement behavior in double quotes; precede the dollar sign with a backtick to override that behavior and not replace the variable. However, in your example, you can't do what you're asking. The use of single quotes turns off the variable replacement behavior, period. It seems like you might want:

    $varA = "VarB=(backtick)"C:\Temp\$Var01(backtick)""

    Replacing the (backtick) placeholders with actual backticks. Those will escape the double quotes that they immediately precede, causing them to be treated as literals rather than as string terminators.

  • #23645

    Topics: 16
    Replies: 22
    Points: 2
    Rank: Member

    Lightbulb went off.

    This works:

    $VarA= "VarA= `"C:\TEMP\{0}`"" -f $Var01

    Kept searching after my post, and found this solution too.

    $PATH = "C:\Test"
    $var01 = "MyVar01"
    $var02 = "MyVar02"
    $hash = @{'PATH' = "$Path\$Var01";
                'Vars' = $Var02;}
    $PathHash = ("PATH=",$hash.PATH)
    $PathHash02 = ("PATH= `"{0}\{1}`"" -f $hash['PATH'],$hash['Vars'])

    Results in: PATH= "C:\Test\MyVar01\MyVar02"

The topic ‘Escaping variables’ is closed to new replies.