Monitor Time and Add a Timeout to Your Long Running Powershell Process

Adam Bertram

Adam Bertram

Read more posts by this author.

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..."
            ## 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
        		## 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

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!