我正在尝试使用powershell创建一个唯一的文件夹名称。这导致无限循环。 else部分中的代码永远不会执行,它试图使文件夹名称唯一。
$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
}
}
你看到我在这里做错了吗?
感谢。
答案 0 :(得分:2)
我建议您使用ISE并使用断点调试脚本。答案很快就变得明显了。你的do 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