This is a quick script to remove stale datastore entry on a host using a reboot cycle script which puts a host into maintenance mode, reboot, remove from maintenance mode and loop through the remaining hosts of the cluster. This is useful for weekend patches or any other maintenance work.
## Connect to the vCenters
Start-Transcript -path C:\Temp\HostReboot-StuckNvME.txt
$startdate = (get-date)
$filepath = "C:\Temp"
$ClusterName = "DEV-Cluster"
$filename = $ClusterName
### Stop SSH Post Reboot
Get-Cluster $ClusterName | Get-VMHost | ForEach {Stop-VMHostService -HostService ($_ |
Get-VMHostService | Where {$_.Key -eq “TSM-SSH”}) -Confirm:$false}
## Reboot Cycle of all hosts
cd C:\Temp\
(Get-Cluster $ClusterName | Get-VMHost).Name | Out-File $filepath\$filename".txt"
## Reboot Cycle Script block
Get-Content .\$filename".txt" | %{
$Server = $_;
Write-Host -ForegroundColor Green "$Server"
Write-Host -ForegroundColor Yellow "`tServer is entering maintenance mode"
Set-VMHost $Server -State maintenance -Evacuate | Out-Null
Write-Host -ForegroundColor Yellow -NoNewline "`tServer Rebooting"
Restart-VMHost $Server -Confirm:$false | Out-Null
## Wait 1min to check connection state post reboot command
do {
sleep 1
$ServerState = (Get-VMHost $Server).ConnectionState
Write-Host -ForegroundColor Yellow -NoNewline "."
} while ($ServerState -ne "NotResponding")
Write-Host -ForegroundColor Yellow -NoNewline "(Server is down)"
## Wait Another 1min to check connection state up post reboot command
do {
sleep 1
$ServerState = (Get-VMHost $Server).ConnectionState
Write-Host -ForegroundColor Yellow -NoNewline "`."
} while ($ServerState -ne "Maintenance")
Write-Host -ForegroundColor Yellow "(Server Booted Up)"
## Exit Maintenance Mode and once complete move on to next host
Write-Host -ForegroundColor Yellow "`tExiting maintenance mode"
Set-VMHost $Server -State Connected | Out-Null
Write-Host -ForegroundColor Yellow "`tReboot Cycle Done!"
Write-Host ""
}
$enddate = (get-date)
$diff= New-TimeSpan -Start $startdate -End $enddate
Write-Host "It took" $diff " hours to complete the task"
Stop-Transcript
Once completed the stale entry will be removed.