Can someone explain the differences between Invoke-Expression $test and Invoke-Expression -Command $test?

variable test is:

 $test = "notepad.exe myfile.txt" 

4 Answers

Both Invoke-Expression $test and Invoke-Expression -Command $test are the same. Both will put $test into the 'command' parameter that is at position 1. The -Command is and optional parameter name that you can put in.

SYNTAX Invoke-Expression [-Command] <string> [<CommonParameters>] 

They're functionally equivalent. -Command is the only parameter the cmdlet takes that isn't in the CommonParameters set and the first one (by default, since it's the only one) when used positionally.

All you're doing with the second example is being explicit with naming your parameter, instead of relying upon position. That's a good habit to get into. Verbose, but future-proof and it makes your intention crystal clear.

Both are not same :

Invoke-Expression : Runs commands or expressions on the local computer.

Invoke-Command : Runs commands on local and remote computers.

The commands are similar but do behave differently. For instance:

$sb = [scriptblock]::Create( "test-path 'c:'") iex $sb icm $sb 

The iex will produce error while icm will not.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy