[英]Find all .txt files on PC, while excluding multiple paths in Powershell
我想在所有分区中找到所有 .txt 文件,但我不想在 C:\\Windows、C:\\PerfLogs 等文件夹中查找...
我的代码不起作用。
$exl = ("*\PerfLogs\*","*\Program Files*","*\ProgramData\*","*\Windows\*",":\Python*");
foreach($i in (Get-PSDrive).Name -match '^[a-z]$'){
foreach($item in (Get-ChildItem "${i}:\*.txt" -Recurse | Where {$_.FullName -notlike $exl})) {
echo $item.Fullname;}}
请使我的代码资源高效。 让它完全跳过排除的文件夹,甚至不递归到它们中。
奇怪的是我只用 1 个元素运行它,但它仍然不起作用。
foreach($i in (Get-PSDrive).Name -match '^[a-z]$'){ foreach($item in (Get-ChildItem "${i}:\*.txt" -Recurse | Where-Object {$_.FullName -NotLike "Windows"})) { echo $item.Fullname;}}
它仍然打印 C:\\ 中的所有 txt 文件,它忽略异常。
我尝试在单词Windows周围使用通配符,没有它们,结果仍然相同。
还试过 Where -NotContains, -NotIn ....
请自己运行该命令并亲自查看
该-like
和-notlike
运营商只支持单一模式的RHS,而不是一个数组[1],因此$_.FullName -notlike $exl
不会工作按预期。
(它将数组$exl
转换为单个字符串,方法是将数组元素与单个空格作为分隔符连接起来)。
您可以使用带有-wildcard
选项的switch
语句:
$driveRoots = (Get-PSDrive -PSProvider FileSystem).Root
Get-ChildItem -Recurse $driveRoots -Filter *.txt | Where-Object {
switch -wildcard ($_.FullName) {
'*\PerfLogs\*' { break }
'*\Program Files*' { break }
'*\ProgramData\*' { break }
':\Python*' { break }
default { return $True } # doesn't match exclusion -> include
}
return $False # matches exclusion -> exclude
}
虽然此解决方案不会阻止递归到匹配模式的文件夹中,但使用-Filter
参数通过让文件系统提供程序执行初始过滤来大大减少扫描工作。
[1]有一个长期而含情脉脉GitHub上的功能要求,使-like
/ -notlike
与图案排列得工作。
我不是 100% 确定这是否是问题,但如果我记得逗号在 PowerShell 中创建了 can 数组。
,
逗号运算符
作为二元运算符,逗号创建一个数组。 作为一元运算符,逗号创建一个包含一个成员的数组。 将逗号放在成员之前。
来源: https : //docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-6
出于故障排除目的,您可以尝试 1 个目录,而 $exl 变量中没有任何逗号吗?
几个观察:
-NotLike "Windows" #you forgot *, this will only be false when item name is "Windows"
-notlike $exl # not like with array will always return true
尝试使用标准选项进行过滤(过滤/排除/包含)
$files = Get-ChildItem -Path '~' -Recurse -file -Include *.txt -Exclude *anac*, *bz*
虽然不确定是内置过滤器选项还是运算符会加快执行速度,但我认为它无论如何都会扫描所有文件。 您可以尝试只遍历文件夹(而不是递归搜索)并跳过这些文件夹以避免在其中扫描文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.