How to pass an array or multidimensional array as arguments to a scriptblock

Envoyer Imprimer

As the MS PowerShell Team explained in the article How to pass arguments for remote commands, if you are invoking remote commands (invoke-command cmdlet) or starting a background job (start-job cmdlet) you want probably to use local values as arguments.

To manage this, both cmdlets have the option –argumentlist which is permitting to precise an array of arguments to be accessed inside your scriptblock using $args variable.

Example 1:

 

Code:

$ProcessName = "winlogon"
Invoke-Command -ComputerName DC02 -ScriptBlock { Get-Process -Name $args[0] } -ArgumentList $ProcessName

 

 

Example 2:

 

Code:

$ScriptBlock = {
Import-Module ActiveDirectory
Get-ADUser -Filter "sAMAccountName -eq '$($args[0])'" -SearchBase $args[1]
}
Invoke-Command -Computer DC02 -ScriptBlock -ArgumentList "aaugagneur","OU=CORPNET,DC=corpnet,DC=net"

 

 

$args is a variable created automatically by PowerShell which handles any parameters passed as arguments with the option –Argumentlist.

Since the variable $args is an array, you will have issues to pass an array as an argument. Basically, It treats each element of your array as a specific argument.

 

If you want to pass your complete array as a specific argument, you will need to use the syntax (,$MyArray) for –Argumentlist parameter.

Example 3:

 

Code:

$Array = @("red","blue","green")
Invoke-Command -ComputerName DC02 -ScriptBlock { Write-Host "1st item: $($args[0])"; Write-Host "2nd item: $($args[1])"; Write-Host "3nd item: $($args[2])" } -argumentList (,$Array)

 

 

Example 4:

 

Code:

$Array = @("red","blue","green")
Invoke-Command -ComputerName DC02 -ScriptBlock { Write-Host "1st item: $($args[0][0])"; Write-Host "2nd item: $($args[0][1])"; Write-Host "3nd item: $($args[0][2])" } -argumentList (,$array)

Mise à jour le Jeudi, 19 Juillet 2012 21:20