2017-08-02 41 views
1

我想添加3個重試到下面的代碼,從USB複製目錄到一臺機器,並在複製後檢查兩個目錄是否相等。如果3次重試後它們不相等,我想恢復以前的配置文件夾。重試powershell循環

我有如何實現重試

[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

要嘗試的東西比,一旦你需要使用一個循環比較麻煩。 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 
    } 
+0

所以在我的例子中,當目錄不相等時,我會遞減計數器,如果它們相等,則會中斷計數。是或者我需要另一個if語句嗎? – user1984300

+0

你基本上會運行循環,完成你想要完成的工作,如果沒有正確完成,請將數字減1。如果工作完成到你滿意,你可以使用break來早日退出循環。 –