使用Powershell筛选文件扩展名

使用Powershell筛选文件扩展名,powershell,Powershell,我喜欢用预定义的扩展名搜索一些旧文件。(如.doc、.xls、.txt等)在特定文件夹中。 我将扩展放在一个变量中: $wildcards = @(".txt",".doc",".xls") 当我在这个变量中放入一个新值时,它必须改变另一个变量。($collection) 这是我的密码: $folder = Get-ChildItem C:\test\test1\ $date = (Get-Date).Add(-1) $wildcards = @(".txt",".doc",".xls")

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

$wildcards = @(".txt",".doc",".xls")
当我在这个变量中放入一个新值时,它必须改变另一个变量。($collection)

这是我的密码:

$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对象条件将不会以这种方式工作。 它不会过滤扩展。 我如何才能做到这一点?
感谢您的帮助。

您似乎让事情变得复杂了。试试这个-

$folder = Get-ChildItem C:\test\test1\
$wildcards = @(".txt",".doc",".xls")
$files = Get-ChildItem -Path $folderPath | where {$_.extension -in $wildcards}
$files
啊,我知道。谢谢你(维韦克)我注意到这个“-in”参数。