【问题标题】:PowerShell script file modify time>10h and return a value if nothing is foundPowerShell脚本文件修改时间>10h,如果没有找到返回值
【发布时间】:2016-09-02 12:04:48
【问题描述】:

我正在尝试编写一个脚本/一个衬里,它将在特定文件夹中查找 10 多个小时前修改过的文件,如果没有文件,我需要它来打印一些值或字符串。

Get-ChildItem -Path C:\blaa\*.* | where {$_.Lastwritetime -lt (date).addhours(-10)}) | Format-table Name,LastWriteTime -HideTableHeaders"

当有文件时,我得到了想要的结果 修改时间超过 10 小时,但如果有,我还需要它来打印值/字符串 没有结果,以便我可以正确监控它。 这样做的原因是为了监控目的使用脚本/一个衬垫。

【问题讨论】:

    标签: powershell zabbix


    【解决方案1】:

    如果没有找到,那些 cmdlet Get-ChildItem 和 where 子句将返回 null。您将不得不单独考虑这一点。 I would also caution the use of Format-Table for output unless 你只是用它来阅读屏幕。如果你想要一个“单线”,你可以这样做。如果您愿意,所有 PowerShell 代码都可以是单行代码。

    $results = Get-ChildItem -Path C:\blaa\*.* | where {$_.Lastwritetime -lt (date).addhours(-10)} | Select Name,LastWriteTime; if($results){$results}else{"No files found matching criteria"}
    

    您的代码中添加了一个括号,这可能是一个复制工件,我不得不删除。正确编码看起来像这样

    $results = Get-ChildItem -Path "C:\blaa\*.*" | 
        Where-Object {$_.Lastwritetime -lt (date).addhours(-10)} | 
        Select Name,LastWriteTime
    
    if($results){
        $results
    }else{
        "No files found matching criteria"
    }
    

    【讨论】:

    • 谢谢兄弟!这似乎起到了作用,是的,我只对屏幕阅读感兴趣,因为监控平台会寻找某个字符串是否存在。
    猜你喜欢
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 2015-11-22
    • 2021-08-15
    • 1970-01-01
    • 2011-12-27
    相关资源
    最近更新 更多