2014-09-04 70 views
0

我有這段代碼,如果文件被鎖定,我需要循環。 我想要做的是,如果文件被鎖定,腳本進入睡眠狀態10秒鐘,然後返回到if(test-Path)並再次運行,直到文件不再被鎖定。 我只是不理解如何做到這一點,任何幫助表示讚賞。如何讓腳本重新開始

if (Test-Path -Path "$path\*") 
{ 
# Code for directory not empty 

# enumerate the items array 
foreach ($item in $items) 
{ 
    # if the item is NOT a directory, then process it. 
if ($item.Attributes -ne "Directory") 
{ 
     $filePath = $path+$item.name   
} 
    else 
    { 
    } 
     function isFileLocked([string]$LockedPath) 
     { 

     $oFile = New-Object System.IO.FileInfo $LockedPath 
     # Make sure the path is good 
     if ((Test-Path -LiteralPath $LockedPath) -eq $false) 
     {  
      #If file is locked go to sleep for 2 minutes and check again, loop until the file is no longer locked. 
      Start-Sleep -s 10 
      # Go back and check directory again to see if more files have come in 

      #return $false 

     } 

回答

2

如果您希望它回到if語句,您需要使用while或do循環。如果你想讓它跳到foreach循環中的下一個項目,你可以使用continue。幫助about_continue

編輯:例如:

Do { 
Start-Sleep -s 10 
} 
Until (Test-Path $LockedPath) 

#Script block executes as long as condition value = True 
While (! (Test-Path $Lockedpath)) 
{Sleep 10} 

的做,直到更容易在邏輯上使用,但第二個選項的好處是它執行腳本之前測試條件阻止在某些情況下(比如這個),它會更有效率。

+0

很好的答案,但我希望看到一個例子。 – TheMadTechnician 2014-09-04 16:47:00

+0

夠公平的。添加示例以幫助 – 2014-09-04 17:18:29

+0

如果可能,我想回到「if(Test-Path -Path」$ path \ *「)」。 – 2014-09-04 19:08:24