powershell - 循环提前停止

标签 powershell

我正在编写一个应用程序,该应用程序查看目录树并根据上次写入时间和只读属性报告文件夹是否处于非事件状态。

但是,即使有数千个文件夹,我的循环也会在 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 函数调用,它会打印所有文件夹,但随着函数调用,它会在几次迭代后停止。发生了什么事?

最佳答案

您不能将continueForeach-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/

相关文章:

powershell - 如何检查调用者是否设置了 PowerShell 可选参数

powershell - powershell 中 Get-ChildItem 命令的默认结果集顺序是什么?

powershell - 包含双引号和单引号的Powershell变量

powershell - 使用 powershell 设置文本格式并使用新行创建一个新文件

powershell - 从 Samaccountname 获取电子邮件地址

c# - 如何从 C# 中的 Powershell 管道读取错误?

Powershell LDAP - physicalDeliveryOfficeName 未显示

security - 验证 PowerShell PSCredential

windows - 如何让powershell脚本在同一终端执行批处理命令

powershell - 如何在Powershell中逐字读取文件?