我喜欢搜索带有预定义扩展名的旧文件。 (例如.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-Object条件将无法以这种方式工作。 它不会过滤扩展。 我如何实现它的工作原理? 任何帮助表示赞赏。
答案 0 :(得分:1)
您似乎正在使事情复杂化。试试这个-
$folder = Get-ChildItem C:\test\test1\
$wildcards = @(".txt",".doc",".xls")
$files = Get-ChildItem -Path $folderPath | where {$_.extension -in $wildcards}
$files