【发布时间】:2015-11-30 21:09:39
【问题描述】:
由于某种原因,下面的 powershell 代码进入了一个无限循环,我不知道为什么。
最低try 块中的代码无法成功,所以我希望catch 捕获错误,然后循环继续。
但它会无限循环,创建越来越多的子目录。
这是为什么呢?
在 powershell v5.0 上测试
在包含至少一个子文件夹的文件夹中尝试代码,该文件夹本身至少包含一个文件。你会明白我的意思。
Get-ChildItem -Recurse | Where-Object { $_.PSIsContainer} | ForEach-Object {
$path = $_
set-Location $path
#get all items, exclude zip files and folders
$items = Get-ChildItem -Exclude *.zip | Where-Object { -not $_.psIsContainer}
#verify that there are items in this directory, catch errors
if ( $items ) {
$newfld = New-Item -ItemType Directory -name "blabla"
#move items to newly-created folder
Move-Item $items -destination $newfld.Fullname
#try to do something that is destined to fail
try{
[void][System.Reflection.Assembly]::LoadFrom($ZipModule)
}
catch {
Write-Host "No Zip"
}
}
}
【问题讨论】:
-
try{}catch{}在if语句中是怎么回事?字符串"No items"将被解释为$true,完全违背了Test-Path的目的 -
什么意思?语句中的第一个
try{}catch{}是检查文件夹是否包含项目,即$items不为空。 -
您不需要
Test-Path,只需检查$items是否包含任何内容:if($items){ # do stuff } -
@MathiasR.Jessen - 这是非常有用的反馈,谢谢!不过,它根本没有回答我的问题。测试代码,你就会明白我的意思了。
标签: powershell for-loop recursion zip infinite-loop