原貼地址:https://www.pstips.net/accessing-files-and-directories.html
只列出目錄::
Dir | Where-Object { $ -is [System.IO.DirectoryInfo] }
Dir | Where-Object { $.PSIsContainer }
Dir | Where-Object { $_.Mode.Substring(0,1) -eq "d" }
只列出文件:
Dir | Where-Object { $ -is [System.IO.FileInfo] }
Dir | Where-Object { $.PSIsContainer -eq $false}
Dir | Where-Object { $_.Mode.Substring(0,1) -ne "d" }
前面的例子(識別對象類型)是目前速度最快的,而後面的(文本比較)比較複雜和低效。
Where-Object也可以根據其它屬性來過濾。
比如下面的例子通過管道過濾2007年5月12日後更改過的文件:
1
Dir | Where-Object { $_.CreationTime -gt [datetime]::Parse("May 12, 2007") }
也可以使用相對時間獲取2周以內更改過的文件:
1
Dir | Where-Object { $_.CreationTime -gt (Get-Date).AddDays(-14) }