1

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: $$,\$ ...

1
  • 1
    i see you have 2 solutions currently, so this is an aside ... DO NOT use Invoke-Expression if you can avoid it. for the reasoning behind that, look up SQL injection ... it can get nasty if you aint really, really, REALLY careful. Commented Aug 23, 2020 at 13:40

3 Answers 3

3

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 :)

Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.