Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $servers = @('SVR1',SVR2',SVR3',SVR4')
- ## Missing leading ' on SVR2/3/4
- $VMs = Get-VM -ComputerName $servers | Where-Object {$_.Version -like '8.0'}
- ## Not familiar with Get-VM but use -eq rather than -like when possible
- #Get all VM's with Configuration Ver. 8.0
- ## This may be personal preference but comments should go before what it is doing rather than after
- Foreach ($VM in $VMs){
- $State = $VM.State
- $VMName = $VM.Name
- #Get Current VM running state
- try {
- if ($State -like 'Running'){
- ## Use -eq if possible
- Stop-VM -VM $VM
- Write-Host "Stopping VM $VMName" -BackgroundColor Red
- #If VM is running, stop
- ## Move comments before code
- } else {"$VMName is Offline"}
- ## Personal preference again, just always include Write-Host
- }
- catch {
- Write-host "$VMName was unable to be stopped" -
- ## Accidental - left behind
- }
- $maxRepeat = 20
- While((Get-VM -ComputerName $servers -Name $VM.Name).State -like 'Running' -or $maxRepeat -eq 0){
- ## while ( ($VM.State -eq 'Running') -and ($maxRepeat -ne 0) ) {
- Write-Host "VM is still running..." -ForegroundColor Red
- $maxRepeat--
- Start-Sleep -Seconds 60
- ## The state of the VM won't change if you don't call it to stop, right?
- }
- #Check every 60 seconds to see if the VM has stopped running, or break.
- If($maxRepeat -gt 0 -or (Get-VM -ComputerName $servers -Name $VM.Name).State -like 'Off') {
- ## $maxRepeat shouldn't matter, if state is off do the following
- try {
- if((Get-VM -ComputerName $servers -Name $VM.Name).State -like 'Off'){
- ## State will be confirmed off at this point, if statement not needed
- Update-VMVersion -name $VMName -ComputerName $VM.ComputerName -Confirm:$false
- Write-Host "$VMName Configuration has been updated to 9.0"
- }
- }
- catch {
- Write-host "Unable to Update VM Configuration for VM $VMName)"
- }
- }
- If($State -like 'Running'){
- ## Again, not familiar with the VM process but if it's running already does it really need started?
- Start-VM -Name $VMName -ComputerName $VM.ComputerName
- Write-host "Starting Virtual Machine"
- #If VM was initially running, start VM again
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment