使用Powershell过滤文件扩展名

问题描述 投票:0回答:1

我喜欢搜索一些带有预定义扩展名的旧文件。 (如.doc,.xls,.txt等)在特定文件夹中。我把扩展名放在一个变量中:

$wildcards = @(".txt",".doc",".xls")

当我在这个变量中加入一个新值时,它必须改变另一个变量。 ($集合)

这是我的代码:

$folder = Get-ChildItem C:\test\test1\
$date = (Get-Date).Add(-1)
$wildcards = @(".txt",".doc",".xls")


function Get-WildCards { 

$counter = 0;
$counterEnd = $wildcards.Count
$collection = New-Object System.Collections.ArrayList 
$filter = "$" + "_.Extension" + " -like $" + "wildcards[" + $counter + "]}"
$or = " -or "

    for ($counter = 0; $counter -lt $counterEnd; $counter++) {

        $filter = "$" + "_.Extension" + " -like $" + "wildcards[" + $counter + "]}"
        $collection += $filter + $or
    }

$collection = [String]::Join('', $collection)
$collection = $collection.ToString()
$collection = $collection.TrimEnd($or)
} 

Get-WildCards

$folderPath = $folder.FullName

$files = Get-ChildItem -Path $folderPath -File:$true |
 Where-Object {$collection} 

$files

如果我运行此代码,Where-Object条件将不会以这种方式工作。它不会过滤扩展名。我怎样才能实现它的工作原理?任何帮助赞赏。

powershell
1个回答
1
投票

你似乎使事情变得复杂。试试这个 -

$folder = Get-ChildItem C:\test\test1\
$wildcards = @(".txt",".doc",".xls")
$files = Get-ChildItem -Path $folderPath | where {$_.extension -in $wildcards}
$files
© www.soinside.com 2019 - 2024. All rights reserved.