首页 > 解决方案 > Powershell Get Child Item Exclude 在当前目录中不起作用

问题描述

正如我在问题中提到的,这似乎是 Powershell 引擎中的错误。

当我尝试通过排除某些文件类型(扩展名)来打印当前目录(也存在所述powershell脚本)中的文件时,它不会打印任何内容。例如。以下代码在 Powershell 控制台中打印当前文件夹的内容:

gci
gci -pa .

上述两个代码都打印目录内容如下:

Mode                LastWriteTime         Length Name                                                                                     
----                -------------         ------ ----                                                                                     
-a----       20-09-2020     22:37      835799796 file1.mkv                                                                      
-a----       20-09-2020     22:25            148 file1.srt                                      
-a----       23-09-2020     04:53            357 scriptv1.ps1                                                           
-a----       20-09-2020     22:25            678 file1.txt

但是当我运行下面的代码时,它不会打印任何东西,当它必须打印 file1.txt 时:

$excluded = @('*.mkv','*.mp4','*.srt','*.sub','*.ps1')
Get-ChildItem -Exclude $excluded | Write-Host { $_.FullName }

谁能帮助弄清楚为什么会发生以及如何获得我提到的内容?

标签: powershellfilterfile-extensionget-childitemwrite-host

解决方案


-Excludewith的使用Get-ChildItem并不直观。要使用 获得一致的结果Get-ChildItem,您必须使用\*或使用-Recurse开关限定您的路径。如果您不关心递归,则可以使用Get-Item限定\*路径。

# Works but includes all subdirectory searches
Get-ChildItem -Path .\* -Exclude $excluded
Get-ChildItem -Path .\* -Exclude $excluded -File
Get-ChildItem -Path . -Exclude $excluded -File -Recurse

# Best results for one directory
Get-Item -Path .\* -Exclude $excluded

应该使用递归的原因是因为-Exclude值首先应用于值的叶子-Path。如果这些排除中的任何一个与您的目标目录匹配,那么它将被排除并阻止其任何项目被显示。见下文:

$path = 'c:\temp'
# produces nothing because t* matches temp
Get-ChildItem -Path $path -Exclude 't*'

推荐阅读