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: $$,\$ ...
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 :)
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
Invoke-Expressionif you can avoid it. for the reasoning behind that, look upSQL injection... it can get nasty if you aint really, really, REALLY careful.