Guest User

Untitled

a guest
Aug 18th, 2021
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $servers = @('SVR1',SVR2',SVR3',SVR4')
  2. ## Missing leading ' on SVR2/3/4
  3.  
  4. $VMs = Get-VM -ComputerName $servers | Where-Object {$_.Version -like '8.0'}
  5. ## Not familiar with Get-VM but use -eq rather than -like when possible
  6.  
  7. #Get all VM's with Configuration Ver. 8.0
  8. ## This may be personal preference but comments should go before what it is doing rather than after
  9.  
  10. Foreach ($VM in $VMs){
  11.     $State = $VM.State
  12.     $VMName = $VM.Name
  13.     #Get Current VM running state
  14.     try {
  15.         if ($State -like 'Running'){
  16.         ## Use -eq if possible
  17.             Stop-VM -VM $VM
  18.             Write-Host "Stopping VM $VMName" -BackgroundColor Red
  19.             #If VM is running, stop
  20.             ## Move comments before code
  21.         } else {"$VMName is Offline"}
  22.         ## Personal preference again, just always include Write-Host
  23.     }
  24.     catch {
  25.         Write-host "$VMName was unable to be stopped" -
  26.         ## Accidental - left behind
  27.     }
  28.     $maxRepeat = 20
  29.     While((Get-VM -ComputerName $servers -Name $VM.Name).State -like 'Running' -or $maxRepeat -eq 0){
  30.         ## while ( ($VM.State -eq 'Running') -and ($maxRepeat -ne 0) ) {
  31.         Write-Host "VM is still running..." -ForegroundColor Red
  32.         $maxRepeat--
  33.         Start-Sleep -Seconds 60
  34.         ## The state of the VM won't change if you don't call it to stop, right?
  35.     }
  36.     #Check every 60 seconds to see if the VM has stopped running, or break.
  37.     If($maxRepeat -gt 0 -or (Get-VM -ComputerName $servers -Name $VM.Name).State -like 'Off') {
  38.     ## $maxRepeat shouldn't matter, if state is off do the following
  39.         try {
  40.             if((Get-VM -ComputerName $servers -Name $VM.Name).State -like 'Off'){
  41.             ## State will be confirmed off at this point, if statement not needed
  42.             Update-VMVersion -name $VMName -ComputerName $VM.ComputerName -Confirm:$false
  43.             Write-Host "$VMName Configuration has been updated to 9.0"
  44.             }
  45.         }
  46.         catch {
  47.             Write-host "Unable to Update VM Configuration for VM $VMName)"
  48.         }
  49.     }
  50.     If($State -like 'Running'){
  51.     ## Again, not familiar with the VM process but if it's running already does it really need started?
  52.         Start-VM -Name $VMName -ComputerName $VM.ComputerName
  53.         Write-host "Starting Virtual Machine"
  54.         #If VM was initially running, start VM again
  55.     }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment