2014-09-22 71 views
1

我想使用PowerShell創建一個唯一的文件夾名稱。這導致無限循環。 else部分內部的代碼永遠不會執行,它試圖使文件夾名稱唯一。PowerShell循環問題

$dirname = "\\" + $ServerName + "\d$\inetpub\Staging\Cms-" + $today.ToString("yyyyMMdd") 

    $found = 0 
$counter = 1 
$newDirName = $dirname 
Do 
{ 
    $LogMessage = "Checking directory: " + $newDirName 
    write-host "##teamcity[message text='$LogMessage']" 

    if(!(Test-Path $newDirName)) 
    { 
     $dirname = $newDirName 
     $found = 1 
    } 
    else 
    { 
     $newDirName = $dirname + "-v" + $counter 
     $LogMessage = "Checking NEW directory: " + $newDirName 
     write-host "##teamcity[message text='$LogMessage']" 
     $counter++ 
    } 
} 
Until($found -lt 1) 

MD $dirname | Out-Null 
    $LogMessage = "Created directory: " + $dirname 
    write-host "##teamcity[message text='$LogMessage']" 

凡爲以下幾項工作:

if(!(Test-Path $dirname)) 
    { 
     MD $dirname | Out-Null 
     $LogMessage = "Created directory: " + $dirname 
     write-host "##teamcity[message text='$LogMessage']" 

    } 
    else 
    { 
     $dirname = $dirname + "v2" 
     if(!(Test-Path $dirname)) 
     { 
      MD $dirname | Out-Null 
      $LogMessage = "Created directory: " + $dirname 
      write-host "##teamcity[message text='$LogMessage']" 
     } 
     else 
     { 
      $LogMessage = "Unable to deploy, the directory: " + $ServerName + " is already in use." 
      write-host "##teamcity[message text='$LogMessage']" 
      exit 1 
     } 
    } 

你看到的東西,我可能是錯在這裏幹什麼?

謝謝。

回答

2

我建議你使用ISE並使用斷點調試你的腳本。答案很快就會變得明顯。你的while while循環運行,直到$ found小於1.但在do循環中它永遠不會設置爲1以外的任何值,所以它永遠不會出現。我認爲這可能會做你正在尋找的東西。

$dirname = "\\" + $ServerName + "\d$\inetpub\Staging\Cms-" + $today.ToString("yyyyMMdd") 
$newDirName = $dirname 
#Variable to hold a boolean for whether the directory was created or not 
$dirCreated = $false 
do{ 
    #If directory does not exist 
    if(!(Test-Path $newDirName)){ 
     #create it 
     md $newDirName | out-null 
     #set variable that we are testing for to true 
     $dirCreated = $true 
    } 
    else 
    { 
     #directory exists so adjust the name and try again 
     $newDirName = $dirname + "-v" + $counter 
     $counter++ 
    } 
} 
while(!$dirCreated) 
#loops until a directory is created 
+0

謝謝,這工作。 – 2014-09-23 02:08:21