如何从路径数组中删除具有特定文件扩展名的文件路径?

How to remove file paths with a specific file extension from an array of paths?

我有一个包含多个文件路径和多个文件扩展名的数组:

$Array = @("C:\aaa\aaa\abc.txt", "C:\aaa\aaa\bbb.txt", "C:\aaa\aaa\abc.c", "C:\aaa\aaa\abc.h", ...etc)

现在,我想删除所有具有 .txt 扩展名的文件路径并执行了以下操作:

$Array | Foreach {$_ | Where {$_ -notlike "*.txt"}}

它确实删除了 .txt 文件路径。

由于我还是 Powershell 的新手,我想知道这是否是正确的方法,或者是否有更好的解决方案(例如,不使用 Foreach 语句) .

这里实际上不需要 Foreach-Object。只需将数组直接通过管道传送到 Where-Object

PS > $Array = @("C:\aaa\aaa\abc.txt", "C:\aaa\aaa\bbb.txt", "C:\aaa\aaa\abc.c", "C:\aaa\aaa\abc.h")
PS > $Array | Where {$_ -notlike "*.txt"}
C:\aaa\aaa\abc.c
C:\aaa\aaa\abc.h
PS > 

当然,在这种情况下,您可以只对数组本身使用 -notlike

PS > $Array -notlike "*.txt"
C:\aaa\aaa\abc.c
C:\aaa\aaa\abc.h
PS >

这是因为 PowerShell 的所有比较运算符都适用于标量和集合。来自 documentation:

When the input to an operator is a scalar value, comparison operators return a Boolean value. When the input is a collection of values, the comparison operators return any matching values. If there are no matches in a collection, comparison operators do not return anything.