Posted On April 2, 2019

PowerShell: Function to Wait for Service to Be Back Online (After Server Reboots)

kimconnect 2 comments
blog.KimConnect.com >> Codes >> PowerShell: Function to Wait for Service to Be Back Online (After Server Reboots)
Function waitForService{
$testSucceeded=(Test-NetConnection $server -port $port).TcpTestSucceeded
$null=Set-PSBreakpoint -Variable rightNow -Mode Read -Action { $global:testSucceeded = (Test-NetConnection $server -port $port).TcpTestSucceeded }

if (!($testSucceeded)){
    Write-Host -NoNewline "Waiting for $server to come back online."
    $dots=50
    $timeout=300 #5 minutes
    while (!($testSucceeded)) {
        $dots-=1;
        $timeout-=2;
        if($timeout -lt 0){"$timeout seconds have passed. Skip this waiting.";continue;}
        if ($dots -eq 0){Write-Host ".";$dots=92;}
        else {Write-Host -NoNewline "."}
        Start-Sleep -s 2
    }
    write-host "$server is now reachable via port $port" -ForegroundColor Green
}else{
    write-host "$server is reachable via port $port" -ForegroundColor Green
    }
}

waitForService

2 thoughts on “PowerShell: Function to Wait for Service to Be Back Online (After Server Reboots)”

  • Hi,

    any idea how to resolve ?

    .Method invocation failed because [System.Boolean] does not contain a method named ‘Refresh’.
    At line:15 char:5
    + $testSucceeded.Refresh()
    + ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

    Tanks 🙂

    • I’ve forgotten to add a line. Retry and let me know if that works. Thanks,

      $null=Set-PSBreakpoint -Variable rightNow -Mode Read -Action { $global:testSucceeded = (Test-NetConnection $server -port $port).TcpTestSucceeded }

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

Repair VSS in Windows 2008

net stop “System Event Notification Service”net stop “Background Intelligent Transfer Service”net stop “COM+ Event System”net…

PowerShell: How To Configure Static IP Address

$nicName='NIC1' $ipaddress='192.168.0.222' $cidrPrefix=24 $defaultGateway='192.168.0.1' $dnsServers=@('8.8.8.8','4.4.2.2') $disableIpv6=$true function setNic($nicName,$ipAddress,$cidrPrefix,$defaultGateway,$dnsServers,$disableIpv6=$true ){ $ifIndex=(get-netadapter|?{$_.Name -eq $nicName}).ifIndex New-NetIPAddress -InterfaceIndex $ifIndex…

Update Windows with Restricted Internet Access

This script is an extract of a longer version with the features of simultaneous executions…