问题描述
我想编写一个 PowerShell 脚本,该脚本将递归搜索目录,但排除指定的文件(例如,*.log
和 myFile.txt
),并且还排除指定的目录及其内容(例如,myDir
和 myDir
下的所有文件和文件夹).
我一直在使用 Get-ChildItem
CmdLet,以及 Where-Object
CmdLet,但我似乎无法得到这个确切的行为.
Get-ChildItem cmdlet 有一个 -Exclude
参数,很容易使用,但它不能用于过滤掉整个目录据我所知.尝试这样的事情:
I want to write a PowerShell script that will recursively search a directory, but exclude specified files (for example, *.log
, and myFile.txt
), and also exclude specified directories, and their contents (for example, myDir
and all files and folders below myDir
).
I have been working with the Get-ChildItem
CmdLet, and the Where-Object
CmdLet, but I cannot seem to get this exact behavior.
The Get-ChildItem cmdlet has an -Exclude
parameter that is tempting to use but it doesn't work for filtering out entire directories from what I can tell. Try something like this:
function GetFiles($path = $pwd, [string[]]$exclude) { foreach ($item in Get-ChildItem $path) { if ($exclude | Where {$item -like $_}) { continue } if (Test-Path $item.FullName -PathType Container) { $item GetFiles $item.FullName $exclude } else { $item } } }
这篇关于如何从 PowerShell 检索递归目录和文件列表,不包括某些文件和文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!