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?

1
  • In short: An executable path that is quoted or contains variable references must - for syntactic reasons - be invoked with &, the call operator; see the linked duplicate for details. Commented Jun 29, 2022 at 14:17

2 Answers 2

3

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

& $Env:SystemRoot\system32\cmd.exe

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

Comments

2

You can use call operator

& "$Env:SystemRoot\system32\cmd.exe"

2 Comments

Thanks for adding a source! I will have a look at it
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.