Ever started a process in Powershell that takes forever only to just end up staring at the last line you put in your Write-Host or Write-Verbose message not really knowing what's going on?

Here's a neat way to let you know every X seconds that the process is still running.

In my situation I was iterating through a set of servers. Some servers were taking much longer than others to process. I needed a quick way to see how long each server was taking.

Since I didn't need any kind of formal time output this method using simple Write-Verbose output worked great. Before I get comments like "Why didn't you use jobs, a parallel foreach in a workflow or parallel runspaces?" each server depended on the previous so I couldn't run this asynchronously.

If asynchronous processing could have been done I'd definitely recommend that over this process.

$Timeout = 600 #10 minutes
$ReportEvery = 15 #Report still waiting every 15 seconds
foreach ($Server in $Servers) {
    try {
        ## Set/reset the timer
        $i = 0
        Write-Verbose "Processing server $Server..."
        while (ADD WHATEVER CONDITION YOURE CHECKING FOR HERE) {
            ## If the server hits the timeout
            if ($i -eq $Timeout) {
                throw "Replication time exceeded timeout of $Timeout seconds for server '$Server'"
    		} else {
        		sleep 1
        		## Add a second to the timer
                $i++
        		## Use the Powershell modulus to only report every so often
                if (($i % $ReportEvery) -eq 0) {
        			Write-Verbose "Not done yet after $i seconds..."	
        		}
            }
    	}
	} catch {
        Write-Error $_.Exception.Message
    }
}

Join the Jar Tippers on Patreon

It takes a lot of time to write detailed blog posts like this one. In a single-income family, this blog is one way I depend on to keep the lights on. I'd be eternally grateful if you could become a Patreon patron today!

Become a Patron!