1

I want to add 3 retries to the following code that copies a directory from a USB to a machine and after the copy it checks if two directories are equal. If after 3 retries they are not equal, I want to restore the previous config folder.

I am having trouble with how to implement the retries

[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

if (Test-Path "D:\Upgrade\CONFIG") { $src_dir = "D:\Upgrade\CONFIG" }
elseif (Test-Path "F:\Upgrade\CONFIG") { $src_dir = "F:\Upgrade\CONFIG" }
elseif (Test-Path "G:\Upgrade\CONFIG") { $src_dir = "G:\Upgrade\CONFIG" }
else { $src_dir = "E:\Upgrade\CONFIG" }

$dest_dir = "C:\TEST\CONFIG"
$date_str = Get-Date -UFormat %d%b%Y
$time_str = Get-Date -UFormat %H%M%S
$archive_dir = "$dest_dir" + "." + "$date_str" + "." + "$time_str"

if (Test-Path $src_dir) { Ren "$dest_dir" "$archive_dir" -verbose; Copy-Item "$src_dir" "$dest_dir" -recurse -verbose }
else { [System.Windows.Forms.MessageBox]::Show("$src_dir found, could not complete !!!") }

$currentConfig = Get-ChildItem -Recurse $dest_dir | Where-Object { -not $_.PsIsContainer }


# NEED HELP WITH ADDING RETRIES HERE


$currentConfig | ForEach-Object {

 # Check if the file, from $dest_dir, exists with the same path under $src_dir
    If ( Test-Path ( $_.FullName.Replace($dest_dir, $src_dir) ) ) {

        # Compare the contents of the two files...
        If ( Compare-Object (Get-Content $_.FullName) (Get-Content $_.FullName.Replace($dest_dir, $src_dir) ) ) {

            # List the paths of the files containing diffs
            $_.FullName
            $_.FullName.Replace($dest_dir, $src_dir)

        }
    }   
}

1 Answer 1

1

To try something more than once you will need to use a loop. Either a While loop or a Do While Loop. Basically, you would create a variable with a number value, and count down from that number. If at the end all three tries have been hit then the script can reset the config.

    $maxTries = 3
    While($maxTries -gt 0){
       # do work here
       # if process fails subtract 1 from maxTries
       # if process succeeds break out of looop
    }
Sign up to request clarification or add additional context in comments.

2 Comments

so in my example, I would decrement the counter when the directories are not equal, and break if they are equal. Is that it or do i need another if statement?
You would basically run the loop, do the work you want to be done, and if it's not done correctly reduce the number by 1. If the work is completed to your satisfaction you can use break to break out of the loop early.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.