1

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?

2
  • Can you say what the error is and how do expect it to work?
    – Stoleg
    Jun 5, 2013 at 12:52
  • It's a syntax error, or my command is launched without parameters, so when I run $path /q /v, PS runs $path instead.
    – Sam
    Jun 5, 2013 at 13:01

2 Answers 2

3

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.

1
  • This is the best way, IMHO.
    – nabrond
    Jun 6, 2013 at 4:41
2

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;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.