PowerShell get-childitem与长路径前缀(\\?\)

uqcuzwp8  于 2023-08-05  发布在  Shell
关注(0)|答案(1)|浏览(188)

我在这两种情况下有不同的结果:

  • 案例1:Get-ChildItem -Path "\\?\UNC\very\long\path"
  • 案例二:Get-ChildItem -Path "\\very\long\path"

如果长路径的长度小于260个字符,我会得到不同的结果。

  • case 1:返回零个子项。
  • 情况2:所有子项都是预期的。

为了得到相同的结果,我应该在情况1中做不同的事情:

Get-ChildItem -Path "\\?\UNC\very\long\path\*"

字符串
为什么会有这种差异?我使用\\?\UNC前缀,因为完整路径是可变的,我不知道它。
也许我应该在这两种情况下使用\*通配符?

nhaq1z21

nhaq1z211#

您在 Windows PowerShell 中看到**一个 bug,当您使用长路径前缀(本地路径为\\?\,UNC路径为\\?\Unc\)将 literal 路径(非通配符)传递到(可能是位置暗示的)-Path参数时,该bug会出现。详情见底部。
要解决这个问题,使用-LiteralPath参数,这对非wildcard路径来说是正确的:

Get-ChildItem -LiteralPath \\?\UNC\server1\share1\very\long\path

字符串
注意事项:

  • PowerShell (Core) 7+不再受影响,因为它对长路径有 * 隐式 * 支持;也就是说,您不再需要长路径前缀
  • 但是,这些前缀仍然应该是 * 接受 * 的,这是 * 部分中断 * 的,至少到PowerShell 7.3.5 -请参阅GitHub issue #10805
    Windows PowerShell bug详情:

当您将具有长路径前缀的非通配符 * 根 * 路径传递给-Path时,该错误就会出现,这适用于使用本地和UNC形式的前缀,尽管症状不同:

# UNC root path: 
# NO OUTPUT
Get-ChildItem -Path \\?\UNC\server1\share1

# LOCAL root path:
# -> SPURIOUS ERROR "Cannot retrieve Cannot retrieve the dynamic parameters for the cmdlet. ..."
Get-ChildItem -Path \\?\C:\

  • 追加至少一个额外的路径组件 * 使问题消失;例如:
# Both OK, due to addition of another path component.
Get-ChildItem -Path \\?\UNC\server1\share1\subfolder
Get-ChildItem -Path \\?\C:\Windows


然而,奇怪的是,local 形式在驱动器 root 级别上不支持 * 通配符 *:

# !! NO OUTPUT
Get-ChildItem -Path \\?\C:\*

# By contrast, wildcards DO work with the UNC prefix at the 
# top-level of the share
Get-ChildItem -Path \\?\UNC\server1\share1\*


顺便说一句:

  • 无论是否使用长路径前缀,UNC * 共享 * 名称的通配符匹配都不受支持,并且会悄悄返回 nothing
  • 也就是说,您不能使用*来发现给定服务器上的可用共享;像Get-ChildItem -Path \\server1\*Get-ChildItem -Path \\?UNC\server1\*这样的东西永远不会产生输出。

相关问题