Run command after sleep if previous execution of the command failed

There are times when you have to execute a command again after sleeping for a few seconds if the previous execution of the command did not give the desired output.
This is the quick and dirty way of getting this to work. I would not take complete credit of this as I had some help from Jonathan Warnken at powershell.org community. As an example I have used netdom command
# Set Number of retries, Delay
    $retries = 5
    $secondsDelay = 10
    $retrycount = 0
    $completed = $false
         
        while (-not $completed){
# Run Command and Pass the Output into a File
            & netdom Join $env:COMPUTERNAME /PasswordM:$env:COMPUTERNAME$ /Domain:DM.COM\RODC0001.dm.com /ReadOnly | Out-File "C:\Join.txt"
            $a = Get-Content -Path "C:\Join.txt"
# Verify the command was successful
            if ($a -eq "The command complete successfully."){
                Write-Output ("Command succeeded.")
                $completed = $true
            }
# Sleep for few seconds and retry again until the retry count
            else                     
            {
                if ($retrycount -ge $retries){
                    Write-Output ("Command failed the maximum number of $retrycount times.")
                    break
                } else {
                    Write-Output ("Command failed. Retrying in $secondsDelay seconds.")
                    remove-item -path "C:\Join.txt" -force
                    Start-Sleep $secondsDelay
                    $retrycount++
                }
            }
    }
Here is the script in action:

Rerun_Cmd

!! Preenesh

Advertisements
This entry was posted in Powershell and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s