【问题标题】:Powershell odd behavior with Get-ChildItem and wildcard in path路径中带有 Get-ChildItem 和通配符的 Powershell 奇怪行为
【发布时间】:2015-06-03 12:11:27
【问题描述】:

Windows 8.1 企业版

    $PSVersionTable.PSVersion
    Major  Minor  Build  Revision
    -----  -----  -----  --------
    4      0      -1     -1

这就是我所看到的。我在子目录“level2”中有一个文件“commands2.txt”。为简单起见,它是“测试”结构中的唯一文件。 完整路径 c:\users\chris\testing\level2\commands2.txt

设置 从 c:\users\chris\testing 作为当前目录。

    $stuff  = gci c:\users\chris\testing\ -Recurse command*.txt
    $stuff2 = gci c:\users\chris\testing\* -Recurse command*.txt

现在,

    get-item $stuff 

返回“get-item:找不到路径 'C:\Users\chris\testing\commands2.txt',因为它不存在。”请注意,缺少“level2”。它看起来只是将 .Name 附加到当前路径。

但是

    get-item $stuff2 

返回完整路径文件的获取项的预期结果。

奇怪吧?所以这就是我感到困惑的地方。

    Compare-Object $stuff $stuff2

表明它们是不同的。

    InputObject                                                 SideIndicator
    -----------                                                 -------------
    C:\users\chris\testing\level2\commands2.txt                 =>
    commands2.txt                                               <=

但是:

    $a = $stuff | select *
    $b = $stuff2 | select *
    compare-object $a $b -includeEqual

表明它们是相同的。 我知道我可以通过在路径中添加“*”来解决这个问题。

但是为什么变量不同,我怎么知道?

为什么 InputObject 不一样?

有没有办法查看 $stuff 和 $stuff2 这两个变量之间的区别?

更新:Vesper 基本上做到了。在这里使用 get-childitem 和 tostring 搜索返回了有用的问题。我的似乎是其他几个的变体。 Mysterious different conversion to string[] of seemingly same input data 显示正在发生的事情。此外,这里还有一个 2010 年的错误报告:https://connect.microsoft.com/PowerShell/feedback/details/556004/get-childitem-gets-fileinfo-constructed-in-different-ways-depending-on-parameters 基于之前的链接。好时光。

【问题讨论】:

  • 您应该使用get-item $stuff.FullNameget-item $stuff.PSPath,而不仅仅是get-item $stuff
  • 我会说这是一个错误,因为行为不一致。
  • @Petseral 是的,我可以做到。我也可以做 $stuff = (gci c:\users\chris\testing\ -Recurse command*.txt).fullname。问题不在于修复它,而在于“它为什么要这样做?”和“你怎么能看到两者之间的实际区别?”

标签: powershell


【解决方案1】:

差异非常微妙,您可以通过他们的toString() 结果来区分它们。

 PS > $stuff.toString()
 commands2.txt    
 PS > $stuff2.toString()
 C:\users\chris\testing\level2\commands2.txt 

MSDN 上有一些数据here 表明toString() 并没有始终如一地返回文件的全名。你似乎遇到了这个问题。我说这是一个错误,但有一种方法可以通过查询toString() 并检查fullName 来查找错误是否触发。

 if ($stuff.toString() -ne $stuff.fullName) { Write-Host "Bug!" }

【讨论】:

  • tostring() 是我需要的!我仍然对此不满意,而且您不能轻易地公开变量的所有属性以进行比较,这是一种痛苦。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 2020-05-06
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多