Reply to Message

View discussion in a popup

Replying to:
plaman
Enthusiast
Enthusiast

run powercli function as job

I have multi vCenters I need to run yum update to all Linux servers, on all sites, so I have written an update function

I need to run that inside a job script, and return the result, the job is stuck at running

 

function Update-VM {

 

   [CmdletBinding()]

   Param(

       [Parameter(Mandatory = $true, ValueFromPipeline = $true)]

        $vm

   )

 

   Import-Module VMware.VimAutomation.Core

   # Take a snapshot of the virtual machine

   Write-Host "Taking a Sbapshot For $vm..." -ForegroundColor Green

  

   $snapshot = New-Snapshot -VM $vm -Name $snapshotName -Description "Snapshot taken before update" -Confirm:$false

  

   # Update the virtual machine using yum

   $updateCommand = " yum update -y"

   $Push=(Invoke-VMScript -VM $vm -GuestCredential $LinCredentials -ScriptText $updateCommand -ScriptType Bash).ScriptOutput

   # Restart the virtual machine

   Restart-VMGuest -VM $vm -Confirm:$false

 Write-Host "passed 3"

   # Wait for VMware Tools to start

 

  

   do {

         $CheckPower=Check-Connection -IP $Ip -vmname $vm -vCentre $vCentre -ConnectionRequest "STARTINGUP"                                                                          

         $PingStatus    =$CheckPower[0]

         $VMPowerStatus =$CheckPower[1]

  

   } until ($PingStatus -eq "Reachable")

 

   # Check if the virtual machine is running

   if ((Get-VM -Name $vm).PowerState -eq "PoweredOn") {

       # Create a test directory on the virtual machine

       $testDir = "/etc/checkarcher"

       $testCommand = "mkdir $testDir"

       Invoke-VMScript -VM $vm -GuestCredential $LinCredentials -ScriptText $testCommand -ScriptType Bash

 

       # Check if the test directory exists

       $testDirExists = Invoke-VMScript -VM $vm -GuestCredential $LinCredentials -ScriptText " ls -d $testDir >/dev/null 2>&1 && echo ""Directory exists"" || echo ""Directory does not exist"""  -ScriptType Bash | Select-Object -ExpandProperty ScriptOutput

 

        $testDirExists= $testDirExists.Trim()

       # Remove the test directory if it exists

       if ($testDirExists -eq "Directory exists") {

           $removeCommand = "rm -r $testDir"

           Invoke-VMScript -VM $vm -GuestCredential $LinCredentials -ScriptText $removeCommand -Server  $vCentre -ScriptType Bash

           Write-Host "Virtual machine $($vm) successfully updated and restarted."

       } else {

           Write-Warning "Virtual machine $($vm) failed to start after update."

       }

   } else {

       Write-Warning "Virtual machine $($vm) failed to restart after update."

   }

 

}

Reply
0 Kudos