Automation

 View Only
  • 1.  start-job re-connect to vcenter in each loop

    Posted Oct 02, 2022 08:04 PM

    Hello team,

     

    I'm trying to validate local admin credential on all VMs by a script (referencing with below two articles)

    #1  https://www.lucd.info/knowledge-base/running-a-background-job/

    #2   https://communities.vmware.com/t5/VMware-PowerCLI-Discussions/Execute-multiple-Powershell-tasks-in-parallel/td-p/1842252

     

    I get to the point where start-job starts re-connect to vcenter in 'foreach' and each connection will take ~30 seconds

    I assumed that With the SessionId parameter, the start-job will  reuse the existing connection rather than create a new vcenter connection from scratch ?

    not sure what is wrong with my script

    ####output####

     

    Golden275_0-1664740569267.png

     

     

    ###Script###

    $code = {
    param(
    [string]$Server,
    [string]$SessionId,
    [string]$VMName
    )

    Set-PowerCLIConfiguration -DisplayDeprecationWarnings $false -Confirm:$false | Out-Null
    Connect-VIServer -Server $Server -Session $SessionId
    Invoke-VMScript -VM $vm -GuestUser "./XXXXXXX" -GuestPassword "XXXXXXX" -ScriptText "" > $null
    }

    $vms=Get-VM | Where-Object {$_.PowerState -eq "PoweredOn" -and $_.ExtensionData.Config.GuestFullName -like "*Microsoft*" }

    $HashJob = @{
    ScriptBlock = $code

    }

    $results = @()

    foreach ($vmName in $vms){
    $j= Start-Job @HashJob -ArgumentList @($global:DefaultVIServer.Name, $global:DefaultVIServer.SessionId, $vmName)


    Receive-Job -Job $j -Wait

    $row3= new-object -TypeName PSObject -Property @{

    'VM_name' = $vmName

    'Job_ID' = $j.Id

    'vspherename' = Receive-Job -Id $j.Id -keep

    }

    $results += $row3

    }
    $results

     

     

     

     

     

     

     

     

     

     



  • 2.  RE: start-job re-connect to vcenter in each loop
    Best Answer

    Posted Oct 02, 2022 08:11 PM

    I'm not sure what you consider as going wrong.
    The Connect-VIServer with the Session parameter re-establishes the existing connection.

    But I don't see what the advantage of the Start-Job is in this case.
    You run the Start-Job and Receive-Job with the Wait option inside the foreach loop.
    None of the background jobs will run in parallel, but one by one.



  • 3.  RE: start-job re-connect to vcenter in each loop

    Posted Oct 02, 2022 08:42 PM

     

    thank you for the clarifications

    yes, I tested in a different way for 20vms that shows below and this time it runs cred check in one shoot and all machines validation complete in less than ~50 sec.

     

    $v = Get-VM | Where-Object {$_.PowerState -eq "PoweredOn" -and $_.ExtensionData.Config.GuestFullName -like "*Microsoft*" }

    Invoke-VMScript -vm $v -GuestUser ".\XXXXX" -GuestPassword "XXXXX" -ErrorAction stop -ScriptText $script > $null