ken
ken

Reputation: 127

How to escape a variable in a string, PowerShell

In my code, I try to keep a command in a string; to then pass it as a parameter to Invoke-Expression. But the variable is evaluated before

$command = "Get-Process | Where-Object { $_.Id -lt 1 }"
Invoke-Expression $command

I tried: $$,\$ ...

Upvotes: 1

Views: 7844

Answers (3)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

The escape sequence character you're looking for is the backtick (`)!

From the about_Quoting_Rules help topic:

To prevent the substitution of a variable value in a double-quoted string, use the backtick character (`)(ASCII 96), which is the PowerShell escape character.

"This string contains a `$dollar sign that won't be expanded"

In my code, I try to keep a command in a string; to then pass it as a parameter to Invoke-Expression

As a general rule of thumb, don't do that - you'll end up handing control over what code executes in your script or function to the calling user.

In your example, simply executing the code directly should suffice:

Get-Process | Where-Object { $_.Id -lt 1 }

If you have a specific use case you can't figure out to rewrite without Invoke-Expression then please update the question with it :)

Upvotes: 3

Hackoo
Hackoo

Reputation: 18827

You should replace the double quotes " by the simple one '

$command = 'Get-Process | Where-Object { $_.Id -lt 1 }'
Invoke-Expression $command

Upvotes: 3

philmph
philmph

Reputation: 143

You can use the typeacceletator [scriptblock] for System.Management.Automation.ScriptBlock and create this way

C:\> $command = [scriptblock]::Create('Get-Process | Where-Object { $_.Id -eq 3320 }')
C:\> invoke-command $command

 NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
 ------    -----      -----     ------      --  -- -----------
     27    27,49      25,77       0,14    3320   1 ApplicationFrameHost

Upvotes: 1

Related Questions