powershell - 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 }
谁能帮助弄清楚为什么会发生以及如何获得我提到的内容?
解决方案
-Exclude
with的使用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*'
推荐阅读
- node.js - 使用 SSL 和 Cloudflare 的 NodeJs 应用程序变慢
- excel - 尝试使用 if 语句来获取单元格中的 exordium right bij 文本
- java - 如何使用firebase将OTP发送到手机号SpringBoot?
- ubuntu - 与原生 Windows NPM/Yarn 处理相比,为什么 WSL 非常慢?
- javascript - 如何根据其值突出显示表格中的单元格
- python - 未检测到安装在同一文件夹中的依赖项?
- javafx - JavaFX 中的按键侦听器在按下按钮时发生变化
- java - java.net.SocketException:将服务从 Java 8 升级到 Java 11 时管道损坏(写入失败)
- spring-boot - 在vaadin的每一页前制作过滤器的最佳方法是什么
- algorithm - 公式,圆的周长与矩形的角相交