2

I want to run some executable on Windows using PowerShell. Path to this executable should be resolved with environment variable.

For example

running command

C:\Windows\system32\cmd.exe

as

$Env:SystemRoot\system32\cmd.exe

I have tried this option and it raises following exception

At line:1 char:16
+ $Env:SystemRoot\system32\cmd.exe
+                ~~~~~~~~~~~~~~~~~
Unexpected token '\system32\cmd.exe' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

What is the right way to do it?

pL3b
  • 1,155
  • 1
  • 3
  • 18
  • In short: An executable path that is _quoted_ or contains _variable references_ must - for syntactic reasons - be invoked with `&`, the [call operator](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#call-operator-); see the linked duplicate for details. – mklement0 Jun 29 '22 at 14:17

2 Answers2

3

Tell the powershell to call the command by putting an ampersand in front

& $Env:SystemRoot\system32\cmd.exe

scaler
  • 417
  • 1
  • 9
2

You can use call operator

& "$Env:SystemRoot\system32\cmd.exe"
Puelloc
  • 101
  • 3
  • Thanks for adding a source! I will have a look at it – pL3b Jun 29 '22 at 13:43
  • As an aside: While it never hurts to enclose variable-based paths in `"..."`, it isn't strictly necessary if the path doesn't contain spaces (or other PowerShell metacharacters), such as in this case. – mklement0 Jun 29 '22 at 14:23