【问题标题】:How to filter subdirectories based off the item count in Powershell如何根据 Powershell 中的项目计数过滤子目录
【发布时间】:2019-04-24 06:43:45
【问题描述】:

我正在尝试根据每个文件夹中的文件数来过滤文件夹。

如果值大于 1,我已经能够列出文件夹名称和值。我正在尝试排除可能不包含任何项目的文件夹。

物品的数量每天都在变化。

$Date2 = Get-Date -Format "yyyy-MM-dd"
$Date2Str = '{0:yyyy-MM-dd}' -f $Date2

$startFolder = "U:\test"

#Returns the Count of files in each queue
$colItems = (Get-ChildItem $startFolder -recurse | Where-Object 
{$_.PSIsContainer -eq $True}  | Sort-Object) 

if($colItems -ine $null){

foreach ($i in $colItems)
 {
     $subFolderItems = (Get-ChildItem $i.FullName | Where-Object 
($_.CreationTime -lt $Date2Str -and $_.Name -like "*.tif"))
    $i.Name + " -- " -f ($subFolderItems.Count) |Format-Table 
@{Expression={$colItems -ge 1}} 

我希望 $colItems 的输出是子文件夹名称和计数,不包括 Count 小于 1 或等于 0 的任何子文件夹。

实际返回的是包含所有子文件夹的子文件夹名称和计数的列表,包括计数等于 0 的子文件夹。

【问题讨论】:

  • 您是否特别需要在 PowerShell 2.0 上运行它? (在以后的版本中,$_.PsIsContainer 有更简单的替代方法)
  • 我对 Powershell 2.0 没有特别的需求。

标签: powershell


【解决方案1】:

如果我的解释正确,您正在寻找这样的东西:

$startFolder = 'U:\test'

Get-ChildItem -Path $startFolder -Directory | 
Select-Object -Property Name, @{Name = 'FileCount'; Expression = { (Get-ChildItem -Path $_.FullName -File).count}}

这会列出您的 $startFolder 的所有子文件夹及其文件数。

顺便说一句:此代码至少需要 Powershell 版本 3。

...当然,您现在可以将其通过管道传输到Where-Object,并仅输出其中包含多个文件的文件夹...

Get-ChildItem -Path $startFolder -Directory | 
    Select-Object -Property Name, @{Name = 'FileCount'; Expression = { (Get-ChildItem -Path $_.FullName -File).count } } |
        Where-Object -Property FileCount -GT -Value 1

【讨论】:

  • 谢谢。这正是我想要完成的。我唯一改变的是Where-Object -Property FileCount -CGE -Value 1。这允许存在超过 1 个文件的任何实例。
猜你喜欢
  • 2014-12-15
  • 1970-01-01
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多