簡體   English   中英

如果有超過 30 天的文件夾

[英]IF there are folders older than 30 days

下面的腳本查找超過 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 中,如何確定命令或表達式是否產生了任何 output?

正如Ash建議的那樣,在幾乎所有情況下,以下內容就足夠了:

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

如果您知道命令或表達式(當它確實產生 output 時)只發出非數字非布爾對象,您可以簡化為以下內容,正如Santiago Squarzon建議的那樣,依賴 PowerShell 的隱式到布爾強制邏輯,總結在這個答案的底部:

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

如果您正在處理將集合(數組)輸出為單個 object的(不尋常的)命令(而不是枚舉集合並分別輸出每個元素,這是正常的管道行為)並且您想要處理一個空集合object 也缺少 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 output 和標量 output object (單個非集合對象),這也適用。 為了統一處理標量和 collections(數組), .Count甚至為本身沒有它的標量添加了一個 .Count 屬性,因此可以將標量視為單元素集合,同樣關於索引 例如(42).Count1 ,並且(42)[0]42 但是,請注意$null.Count0 這種 PowerShell 引擎提供的類型成員稱為內在成員

警告:由於一個長期存在的錯誤 - 在GitHub 問題 #2798中報告,並且在 PowerShell 7.2 中仍然存在 - 如果Set-StrictMode -Version 2訪問本身沒有它的對象上的內在.Count屬性,則會導致語句終止錯誤-Version 2或更高版本已生效。


但是,上面的測試不允許您區分no output和(單個) $null,這需要以下方法- 盡管請注意實際$null output 在 Z3D265B4E003EEF0DCC88 中是不尋常[1

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

This obscure test is necessary, because no output in PowerShell is represented by the [System.Management.Automation.Internal.AutomationNull]::Value] singleton , which behaves like $null in expression contexts, but not in enumeration contexts such as in a管道,包括@(...)數組子表達式運算符,它返回一個數組[System.Management.Automation.Internal.AutomationNull]::Value] (元素計數0 )和一個單元素數組$null

雖然區分$null[System.Management.Automation.Internal.AutomationNull]::Value通常不是必需的,但鑒於它們的枚舉行為不同,肯定存在這種情況。 能夠通過諸如$Test -is [AutomationNull]之類的簡單測試進行區分是GitHub 提案 #13465的主題。


[1] 最好避免從 PowerShell 命令(cmdlet、腳本、函數)返回$null 相反,只需省略 output 命令。 However, .NET API methods may still return $null and object properties may contain $null (even [string] -typed ones, and even in PowerShell class definitions - see GitHub issue #7294 ).

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM