我想在以下代码中添加3次重试,将目录从USB复制到计算机,并在复制后检查两个目录是否相等。如果在3次重试后它们不相等,我想恢复以前的配置文件夹。
我在如何实施重试
方面遇到了麻烦[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)
}
}
}
答案 0 :(得分:1)
要多次尝试,您需要使用循环。 While循环或Do While循环。基本上,您将创建一个带有数字值的变量,并从该数字开始倒计时。如果最后三次尝试都被击中,那么脚本可以重置配置。
$maxTries = 3
While($maxTries -gt 0){
# do work here
# if process fails subtract 1 from maxTries
# if process succeeds break out of looop
}