【问题标题】:How do I locate a specific parent/child using Get-ChildItem?如何使用 Get-ChildItem 定位特定的父/子?
【发布时间】:2019-05-23 20:32:10
【问题描述】:

我可以使用 Get-ChildItem -Recurse 递归搜索目录以定位特定目录,但我只对目录是另一个特定目录的子目录的情况感兴趣。父/子可以存在于目录树中的任意深度。例如:

C:\lev1\lev2\lev3\lev4\parentDir\childDirToFind\lev7...

以下代码返回所有出现的 childDirToFind :

Get-ChildItem -Path C:\\*\\*\ChildDirToFind -Recurse

我尝试在 -Path 选项中包含 parentDir,但没有得到任何结果;例如:

Get-ChildItem -Path C:\\*\\*\parentDir\childDirToFind -Recurse

我也尝试使用 -Filter 选项但没有结果。也许 Get-ChildItem 不是最好的方法?理想情况下,我希望 Get-ChildItem 在找到目录后立即返回,而不是继续搜索整个树。

【问题讨论】:

  • 试试Get-ChildItem -Path c:\ -Recurse -Filter childDirToFind
  • 带别名:gci x:\start -dir -rec -filter childDirToFind |? {$_.Parent.Name -eq 'parentDir'} | select -first 1
  • 顺便说一句,搜索应该停止,第一个找到尾随 \lev7.. 是不可能的。

标签: powershell


【解决方案1】:

这里有一个例子,父是drivers,子是etc

Get-ChildItem C:\Windows -Recurse -Directory -ErrorAction SilentlyContinue | ? { $_.FullName -like '*\drivers\etc' }

我添加了-ErrorAction 参数来隐藏所有无法访问的文件夹错误。

【讨论】:

    【解决方案2】:

    感谢 Rich Moss 和 LotPings 引导我朝着正确的方向前进。两种解决方案都提供了正确的结果,尽管通过管道将输出传递给“select -first 1”确实具有在找到结果后停止目录搜索的额外好处。我不知道为什么,但使用 -filter 和比较 $.Parent.Name 是比较 $.FullName 的两倍(使用 Measure-Command 检查)。我最终选择了这个:

    cgi C:\ -dir -rec -ea SilentlyContinue -filter childDirectory | ? {$_.Parent.Name -eq 'parentDir'} |选择 -first 1

    【讨论】:

      猜你喜欢
      • 2020-04-22
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      相关资源
      最近更新 更多