Reputation: 11
I have a simple question. I would like to assign a command to a variable and execute it with extra parameters, like:
C:\test.exe /q /v
But when I do:
$path=C:\test.exe
$path /q /v
It doesn't work.. Any idea?
Upvotes: 1
Views: 88
Reputation: 201662
The most canonical way to do this is to use the call operator on the variable that contains the "name" of the command e.g.:
& $path /q /v
This is actually required when the path to the command (ie native exe) contains spaces.
Upvotes: 3
Reputation: 5504
Command as string:
With Invoke-Expression cmdlet you execute an arbitrary string as a piece of code. It takes the string, compiles it, and executes it.
So you do:
$path='C:\test.exe';
Invoke-Expression "$path /q /v";
As a side note: When you do $path=C:\test.exe
without the quotes, you are actually assigning the STDOUT of test.exe
to the variable $path
. You have to make clear to PowerShell that it is actually a string you wish to execute later.
Command as script object:
If you are concerned with performance, you could also try converting your command to a compiled scriptblock, and execute it with the &
call operator.
$path='C:\test.exe';
$cmd = [scriptblock]::Create("$path /q /v");
& $cmd;
Upvotes: 2