powershell - 如何在 PowerShell Get-ChildItem 中的通配符模式中使用方括号?

标签 powershell

我想在方括号中列出所有以某些文本结尾的文件。

但是 Get-ChildItem *[*Get-ChildItem *`[*Get-ChildItem *``[* 都不起作用.

我怎样才能毫不费力地完成这项工作(即通过创建变量、通过管道运行其他命令等)

最佳答案

以下内容,包括您尝试过的其中一项,应该工作,但是 currently[1] doesn't work due to a bug :

# SHOULD work, but CURRENTLY BROKEN:
Get-ChildItem *``[*    # 1st ` is for string parsing, 2nd ` for wildcard escaping
Get-ChildItem "*``[*"  # ditto, with double quotes
Get-ChildItem '*`[*'   # single-quoted alternative, requires only 1 `

请注意,使用(第一个)位置参数会隐式绑定(bind)到 Get-ChildItem-Path 参数。

Get-ChildItem 的意图是在参数解析后看到以下文字:*`[*,它正确地转义了 [ ` 以便将其视为文字。

顺便说一句:不带引号的 *`[* 等价于双引号的 "*`[*",结果是文字 *[*,因为 PowerShell 的 字符串解析 会解释 ` 并有效地删除它。

解决方法:

不要转义 [ 字符,而是将其括在 [...] 中,这是一个字符集表达式,这会导致它按字面意思进行匹配:

Get-ChildItem *[[]*  # OK

有趣的是,通过 -Include 执行过滤 not 会出现错误:

Get-ChildItem * -Include '*`[*'  # OK

另一种选择是使用 -Filter 代替(隐含的)-Path,如 Paxz's answer 中所示,但请注意 -Filter 的通配符语言 与 PowerShell 的 相同(由 -Path-Include/-Exclude 参数); -Filter 参数被传递给 Windows API,其通配符语言不同如下:

  • 它支持的结构更少,尤其是不支持字符集或范围([...])。
  • 它有一些遗留的怪癖 - 见 this answer .
  • 从好的方面来说,使用 Filter,由于在源头进行过滤,比让 PowerShell 通过(隐含的)-Path 进行过滤的性能更好>-包括

另一种选择是添加另一层转义,但这是不明智的,因为一旦修复了错误,它将停止工作:

# NOT RECOMMENDED: will stop working once the bug is fixed.
Get-ChildItem '*``[*' 

[1] 自 Windows PowerShell v5.1/PowerShell Core 6.2.0-preview.3 起

关于powershell - 如何在 PowerShell Get-ChildItem 中的通配符模式中使用方括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54094312/

相关文章:

powershell - 如何在Windows Server 2012(AWS EC2)中更改和验证主机名

Azure Devops - 如何在部署后的应用服务上运行 powershell 脚本?

json - 尝试在 JSLint 中验证 JSON 文件时出现解析错误

sql-server - 为 Dacpac 和 Powershell 脚本创建 Nuget 包

powershell - 导出当前 DSC 配置以导入到另一台服务器(以 IIS 网站为例)

python - pipenv shell在虚拟环境中启动子shell… 'powershell.exe'无法识别为内部或外部命令,可操作程序或

regex - 合并不连续区域的文字

powershell - 从Invoke-Command执行的脚本中访问凭据

Powershell - 如何使用 $List.convertAll() 或替代 C# 方法来克隆列表

powershell - 在 Windows 文件共享上设置权限