How to pass arguments in Invoke-Command in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

To pass the argument in the Invoke-command, you need to use -ArgumentList parameter. For example, we need to get the notepad process information on the remote server.

Example

Invoke-Command -ComputerName Test1-Win2k12 -
ScriptBlock{param($proc) Get-Process -Name $proc} -
ArgumentList "Notepad"

Output

Handles NPM(K) PM(K) WS(K) CPU(s)  Id SI ProcessName PSComputerName
------- ------ ----- ----- ------  -- -- ----------- --------------
  67      8  1348  7488   0.08 104    notepad     Test1-Win2k12

In the above example, we are passing "Notepad" name as the argument to the command and the same has been caught by the $proc variable inside Param().

If you have the multiple, check the below command to pass the multiple parameters.

Example

Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock{param($proc,$proc2) Get-Process -Name $proc,$proc2} -ArgumentList "Notepad","Calc"

Output

Handles NPM(K) PM(K) WS(K) CPU(s)  Id SI ProcessName PSComputerName
------- ------ ----- ----- ------  -- -- ----------- --------------
  96     20  5980 11392   0.19 288    calc        Test1-Win2k12
  67      8  1344  7556   0.08 104    notepad     Test1-Win2k12

Same can be achieved with the Session variable.

Example

$sess = New-PSSession -ComputerName Test1-win2k12
Invoke-Command -Session $sess -ScriptBlock{param($proc) Get-Process $proc} -ArgumentList "Notepad"

Output

Handles NPM(K) PM(K) WS(K) CPU(s)  Id SI ProcessName PSComputerName
------- ------ ----- ----- ------  -- -- ----------- --------------
  67      8  1348  7488   0.08 104    notepad     Test1-Win2k12
raja
Published on 11-Nov-2020 11:23:31
Advertisements