Invoke-Command Array in ArgumentList

When dealing with multiple servers, you may often have to run a powershell command or script on many or all of them. This is where "Invoke-Command" comes into play.

The Invoke-Command will execute a powershell command on a remote system and return the results to our powershell console. Let's take a look at a simple example.

We are going to test whether or not a folder exists on multiple servers:

$servers = @("dc1", "dc3")

$servers |
    %{
        Invoke-Command -ComputerName $_ `
                       -ScriptBlock {
                                Write-Output "C:\Temp"
                            }
    }

The Write-Output cmdlet is executed on the dc1 and dc3 servers.

But what if we have to pass parameters to the scriptblock? We will use the -ArgumentList parameter of the Invoke-Command as follows:

$servers = @("dc1", "dc3")

$path = "C:\Temp"

$servers |
    %{
        Invoke-Command -ComputerName $_ `
                       -ScriptBlock {
                                Param ($par1)
                                Write-Output $par1
                            } -ArgumentList $path
    }

A parameter named "par1" is declared on the scriptblock and the "path" variable is passed to the scriptblock using the -ArgumentList parameter. The Write-Output cmdlet is then executed with the $path parameter as input.

There is a caveat here though, when we are trying to pass an array as a parameter. If we pass an array using the -ArgumentList parameter, the array will pass each item in the array as a different parameter to the scriptblock. In order to pass the array as a single parameter we have to use the following syntax:

$servers = @("dc1", "dc3")

$path = @("C:\Temp", "D:\Temp")

$servers |
    %{
        Invoke-Command -ComputerName $_ `
                       -ScriptBlock {
                                Param ($par1)
                                Write-Output $par1
                            } -ArgumentList (,$path)
    }

Popular posts from this blog

Syslog Message Collection for OMS from sources that do not support the agent

How to Configure Message Forwarding on a Mailbox Level

Generating Alerts On OMS