2014-09-04 72 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