Powershell脚本无法在无限循环中运行

时间:2016-05-08 22:05:01

标签: powershell

我试图在无限循环中运行此脚本:

$UNC = "\\pawelu\IELTS9"
$hostname = "pawelu"
$val = 1

start-transcript -path C:\Users\Administrator\Desktop\new.txt -append;

while($true) { 
Get-Date -format o;
start-sleep -s 3; write-host "UNC available... " -nonewline;
test-path $UNC;
$pingTest = test-connection -computername $hostname -count 1 -Quiet;  
write-host "ICMP is succesfull ... " $pingTest
write-host "Can write a file ... " -NoNewline
try {

$testPath = join-path $UNC ([IO.Path]::GetRandomFileName())
new-item -path $testPath -ItemType file -ErrorAction Stop > $null


add-content $testPath SampleText
return $true

}catch
    {return $false
    }
    finally{

         remove-item $testPath -ErrorAction SilentlyContinue
        }
}

然而,在运行一次后它会停止。如果我删除Try,catch并最终阻止它继续我手动停止它,这是我想要的。因此,我认为缺陷在某处,但无法弄明白。如何让这个脚本继续运行?

1 个答案:

答案 0 :(得分:2)

  

如何使此脚本继续运行?

停止制作脚本return

只需从return $true块中删除try语句。

如果您希望循环在发生错误时继续,请同时从return $false块移除catch