我正在编写一个应用程序,该应用程序查看目录树并根据上次写入时间和只读属性报告文件夹是否处于非事件状态。
但是,即使有数千个文件夹,我的循环也会在 7 次迭代后停止。
我的代码如下:
function FolderInactive{
Param([string]$Path)
$date = (Get-Date).AddDays(-365)
$anyReadOnly = $false
Get-ChildItem $Path -File -ErrorAction SilentlyContinue | ForEach-Object {
if($_.LastWriteTime -ge $date){
$false
continue
}
if($_.IsReadOnly -eq $false){
$anyReadOnly = $true
}
}
$anyReadOnly
}
Get-ChildItem "some drive" -Recurse | where {$_.PSIsContainer} | Foreach-Object {
Write-Host $_.FullName
FolderInactive($_.FullName)
}
如果我注释掉 Foreach 循环中的 FolderInactive
函数调用,它会打印所有文件夹,但随着函数调用,它会在几次迭代后停止。发生了什么事?
最佳答案
您不能将continue
与Foreach-Object
cmdlet 一起使用。 Foreach-Object
是一个 cmdlet,不是循环。相反,您想使用循环:
function FolderInactive{
Param([string]$Path)
$date = (Get-Date).AddDays(-365)
$anyReadOnly = $false
$items = Get-ChildItem $Path -File -ErrorAction SilentlyContinue
foreach($item in $items)
{
if($item.LastWriteTime -ge $date){
$false
continue
}
if($item.IsReadOnly -eq $false){
$anyReadOnly = $true
}
}
$anyReadOnly
}
这也可以简化:
function FolderInactive
{
Param([string]$Path)
$date = (Get-Date).AddYears(-1)
$null -ne (Get-ChildItem $Path -File -ErrorAction SilentlyContinue |
Where {$_.LastWriteTime -ge $date -and $_.IsReadOnly})
}
关于powershell - 循环提前停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38116911/