如果存在超过 30 天的文件夹

问题描述

下面的脚本查找超过 30 天的文件夹。如果没有,我只想添加一个简单的 IF 语句来说明“没有超过 30 天的文件夹”。但我不知道该怎么做 谢谢

$Test = Get-ChildItem "\\Server\XFER\Cory" -Directory | 
    Sort LastWriteTime -Descending |
    Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} |
    Select-Object Name,LastWriteTime 

解决方法

你的问题归结为:
在 PowerShell 中,如何确定命令或表达式是否产生任何输出?

几乎所有情况下,以下内容就足够了,正如 Ash 建议的那样:

$Test = ...  # ... represents any command or expression
if ($null -eq $Test) { 'no output' }

如果您知道命令或表达式 - 当它产生输出时 - 只发出非数字非布尔 em> 对象,您可以将简化为以下内容,正如 Santiago Squarzon 建议的那样,依赖 PowerShell 的隐式 to-Boolean 强制转换逻辑,总结在 {{3} 的底部部分}:

$Test = ...  # ... represents any command or expression
if (-not $Test) { 'no output' }

如果您正在处理一个将集合(数组)作为单个对象输出(而不是枚举集合并输出每个元素)的(不寻常的)命令分开,这是正常的管道行为)并且您也希望将空集合对象视为缺少输出

$Test = ...  # ... represents any command or expression
# Caveat: Due to a bug,only works robustly with 
#         Set-StrictMode turned off (the default) 
#         or Set-StrictMode -Version 1 (not higher).
if ($Test.Count -eq 0) { 'no output' } 

请注意,这甚至适用于 $null 输出和标量输出对象(单个非集合对象)。为了统一处理标量和集合(数组),PowerShell 甚至为本身没有的标量添加了 .Count 属性,这样标量就可以被视为单元素集合,也关于索引;例如(42).Count1,而 (42)[0]42;但是,请注意 $null.Count0。此类 PowerShell 引擎提供的类型成员称为 this answer

警告:由于一个长期存在的错误 - 在 intrinsic members 中报告并且从 PowerShell 7.2 开始仍然存在 - 访问对象的内在 .Count 属性如果 GitHub issue #2798 -Version 2 或更高版本有效,它本身会导致语句终止错误


但是,上述测试不允许您区分根本没有输出和(单个)$null,这要求以下方法 - 但请注意实际的 $null 输出在 PowerShell 中不寻常[1]>

$Test = ...  # ... represents any command or expression
if ($null -eq $Test -and @($Test).Length -eq 0) { 'no output' }

这个晦涩的测试是必要的,因为 PowerShell 中的没有输出Set-StrictMode 单例表示,它行为类似于 $null表达式上下文中,但不在枚举上下文中,例如在管道中,包括 @(...)[System.Management.Automation.Internal.AutomationNull]::Value],它返回[System.Management.Automation.Internal.AutomationNull]::Value] 数组(元素计数 0)和 $null单元素 数组。

虽然通常没有必要区分 $null[System.Management.Automation.Internal.AutomationNull]::Value,但肯定有必要区分,因为它们的枚举行为不同。能够通过简单的测试(例如 $Test -is [AutomationNull])进行区分是 array-subexpression operator 的主题。


[1] 最好避免从 PowerShell 命令(cmdlet、脚本、函数)返回 $null;相反,只需省略输出命令。但是,.NET API 方法 可能仍会返回 $null 并且对象属性可能包含 $null(即使是 [string] 类型的,和即使在 PowerShell class 定义中 - 参见 GitHub proposal #13465)。