Home > Software engineering >  How do I invoke a command using a variable in powershell?
How do I invoke a command using a variable in powershell?

Time:12-22

I want to invoke the shutdown.exe executable in powershell and it is located on C:\WINDOWS\System32\shutdown.exe.

Since we already got the C:\WINDOWS in the variable $env:windir I want to just use it and concatenate the rest of the path into the command. I was trying this:

PS C:\Users\shina> .\$env:windir\System32\shutdown.exe -s

But I got the following error:

    .\$env:windir\System32\shutdown.exe: The term '.\$env:windir\System32\shutdown.exe' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

How can I accomplish this?

CodePudding user response:

You can use:

& $env:windir\System32\shutdown.exe -s

Or

. $env:windir\System32\shutdown.exe -s

(note the space).


& is the call operator. You can read more about it here:

Runs a command, script, or script block. The call operator, also known as the "invocation operator", lets you run commands that are stored in variables and represented by strings or script blocks.


. is the dot sourcing operator. You can read more about it here:

Runs a script in the current scope so that any functions, aliases, and variables that the script creates are added to the current scope, overriding existing ones.

The dot sourcing operator is followed by a space. Use the space to distinguish the dot from the dot (.) symbol that represents the current directory.

  • Related