Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array to Get-Job

I am having trouble getting an array passed to a scriptblock in Start-Job. Can you tell me what I might be doing wrong?

$bounceBlock = {
param(
[string[]]$list,
[System.Management.Automation.PSCredential]$cred
)
Add-PSSnapin VMware.VimAutomation.Core | Out-Null
Set-PowerCLIConfiguration -DefaultVIServerMode Multiple -Scope User -InvalidCertificateAction Ignore -Confirm:$false | Out-Null
Connect-VIServer -Server servername -Credential $cred -AllLinked
Get-VM -Name $list
}


if ($targets) {
$activeTargets = $targets | Get-Random -Count $prodTargets.Count
$counter = [pscustomobject] @{Value = 0}
$groupSize = 50
$groups = $activeTargets | Group-Object -Property {[math]::Floor($counter.Value++ / $groupSize)}
$connection = Connect-VIServer -Server servername -Credential $cred -AllLinked
if ($connection -match "servername") {
    foreach ($group in $groups) {
        while ((Get-Job -State Running).Count -ge 5) {
            Start-Sleep -Seconds 5
            }
        Start-Job -ScriptBlock $bounceBlock -ArgumentList (,$group.Group.ServerName),$cred
        }
    Disconnect-VIServer * -Force -Confirm:$false
    }
}

I basically split an array into chunks of 50 (working) then try to run them as jobs. The error I get looks like it's trying to run Get-VM for a single server, named all 50 values appended together.

like image 746
Acerbity Avatar asked Aug 21 '15 14:08

Acerbity


1 Answers

I am certainly no expert with PS, but first to address how you're passing in the appended list of servers; I do something similar with Azure VMs using Get-AzureVM and I pass in my list of VM names in a System.Array to functions or cmdlets such as a variable such as $theVMs= "MyServer1","MyServer2","MyServer3" and then I execute a foreach loop over ($vm in $theVMs) and then perform the actions such as Get-VM sequentially. I do this sequentially since PS has some much lower limits, 5 per my experience, doing this via a parallel for loop.

A typical way I interact with the VMs remotely and create a PS Job per each is to use $uri = Get-AzureWinRMUri -ServiceName $svc -Name $vmname

 Invoke-Command -ConnectionUri $uri -Credential $creds **-JobName 
 $jobname**    
 -ArgumentList $vmname -ScriptBlock {
 param([string]$thevm) ...
 }

This requires the InstallWinRMCertAzureVM.ps1 script which is discussed and available at http://blogs.technet.com . I use this for between 30 servers regularly.

like image 158
SDillon Avatar answered Oct 27 '22 00:10

SDillon