I am performing some configuration settings on all the esx servers.
I perform the configuration change on one server at a time. The server is first put in maintenance mode and then the settings are changed.
After that they get rebooted.
The problem is that when i initiate the reboot, i wan't to verify that the server is notresponding, so that the script has to wait before it continues, then there is a loop that verifies the server i back online again and get's it out of maintenance mode.
The only problem is am facing is that when in reboot the server my session dies.
Here is the code:
#REBOOT THE SERVER
#WAIT UNTIL IT CAN'T BE CONTACTED
$esx.RebootHost($true)
#LOOP
$DISCONNECT = $False
Do
{
$GETHOST = get-vmhost | where {$_.name -eq $ESXHOST}
$GETSTATE = $GETHOST.State
if ($GETSTATE -eq "NotResponding")
{
$DISCONNECT = $True
}
else
{
$DISCONNECT = $False
}
}until($DISCONNECT -eq $True)
#WAIT UNTIL IT'S BACK ONLINE AGAIN
#LOOP UNTIL THE ESX SERVER IS BACK ONLINE
$CONNECT = $False
Do
{
$GETHOST = get-vmhost $ESXHOST
$GETSTATE = $GETHOST.State
if ($GETSTATE -eq "Maintenance" -or $GETSTATE -eq "CONNECTED")
{
$CONNECT = $True
}
else
{
$CONNECT = $False
}
}until($CONNECT -eq $True)
#GET THE HOST OUT OF MAINTENANCE
$esx = Get-VMHost $ESXHOST | Get-View
$taskMoRef = $esx.ExitMaintenanceMode_Task(0)
$task = Get-View $taskMoref
while ($task.info.state -eq "running" -or $task.info.state -eq "queued")
{
sleep 2
$task = Get-View $taskMoref
}
Who has the solution?
I use a function similar to this:
function WaitServerToStart($server, $seconds, $credentials) {
#'Stop' preference with trap block is used instead of 'Continue' preference assuming all the non-terminating errors will terminate Connect-VIServer command without returning value for $conn. We want to prevent a behaviour like this: Connect-VIServer both returns value for $conn and throws non-terminating error and then exit normally from the for cycle.
$ErrorActionPreference = 'Stop'
$succeed = $false
for ($i = 0; $i -lt ($seconds/10); $i++) {
Start-Sleep -s 10
trap {
continue
}
$conn = Connect-VIServer -Server $server.Name -Credential $credentials
#if there is no error the $conn will be not null
if ($conn -ne $null) {
$succeed = $true
break;
}
}
#restore the old preference and $error variable.
if ($succeed) {
Write-Host "Successfully restored server: $($server.Name)"
} else {
throw "The server: $($server.Name) not restored"
}
}
Then I execute the function like this: WaitServerToStart $vmHostObject 360 $vmHostCredentialsObject
\Yavor
Hi Yboychev,
Thanks for your response.
I found what the problem is. I use a connect statement to connect to the esx host, because i have to be connected to the esxhost to use the Get-VMhostModule and Set-VMhostModule.
I put in an extra disconnect-viserver to disconnect from the esx host.
I fixed it.
I created a seperate function to connect to the esx host and change the settings. In the main loop the connection to vcenter stays alive and it works perfectly.