Differences between Invoke-Expression and Invoke-Expression -Command

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

variable test:

  $test = "notepad.exe myfile.txt" 
+4
source share
4 answers

Both Invoke-Expression $test and Invoke-Expression -Command $test same. Both will put $test in the 'command' parameter, which is located at position 1. -Command is the optional parameter name that you can insert.

 SYNTAX Invoke-Expression [-Command] <string> [<CommonParameters>] 
+7
source

They are functionally equivalent. -Command is the only parameter that accepts a cmdlet that is not in the CommonParameters set, and the first (by default, since it is the only one) when it is used positionally.

Everything you do with the second example is explicit with your parameter, instead of relying on position. This is a good habit. Verbose, but in the future, and this makes your intention perfectly clear.

+4
source

The teams are similar, but they behave differently. For instance:

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

iex will give an error, but icm will not.

-one
source

Both are not the same:

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

Invoke-Command . Executes commands on local and remote computers.

-one
source

Source: https://habr.com/ru/post/1500741/


All Articles