【问题标题】:Combine Get-Item with Get-ChildItem?将 Get-Item 与 Get-ChildItem 结合使用?
【发布时间】:2012-08-10 02:18:39
【问题描述】:

我以为我得到了所有的容器 $containers = Get-ChildItem -path $Path -recurse | ? {$_.psIscontainer -eq $true}, 但它似乎只返回了我的$Path 的子目录。我真的希望$containers 包含$Path 及其子目录。我试过这个:

$containers = Get-Item -path $Path | ? {$_.psIscontainer -eq $true}
$containers += Get-ChildItem -path $Path -recurse | ? {$_.psIscontainer -eq $true}

但它不允许我这样做。我是否使用了 Get-ChildItem 错误,或者我如何通过将 Get-Item 和 Get-ChildItem 与 -recurse 组合来让 $containers 包含 $Path 及其 $subdirectories?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    以下内容对我有用:

    $containers = Get-ChildItem -path $Path -recurse | Where-object {$_.psIscontainer}
    

    我最终得到的是$path$path 的所有子目录。

    在您的示例中,您有$.psIscontainer,但它应该是$_.psIscontainer。这也可能是您的命令的问题。

    【讨论】:

    • 我有 $Path = \\share\place ,例如,有两个子目录被调用。当我运行您的建议时,我仍然得到 $containers = {in,out},而不是 {\\share\place,in,out}。这令人困惑。
    • 如果要全名则需要选择全名: $containers = Get-ChildItem -path $Path -recurse | Where-object {$_.psIscontainer} |选择对象全名
    【解决方案2】:

    在您第一次调用 get-item 时,您没有将结果存储在数组中(因为它只有一项)。这意味着您不能在 get-childitem 行中将数组附加到它。只需通过将结果包装在 @() 中来强制您的容器变量成为一个数组,如下所示:

    $containers = @(Get-Item -path $Path | ? {$_.psIscontainer})
    $containers += Get-ChildItem -path $Path -recurse | ? {$_.psIscontainer}
    

    【讨论】:

      【解决方案3】:

      使用Get-Item获取父路径,Get-ChildItem获取父子路径:

      $parent = Get-Item -Path $Path
      $child = Get-ChildItem -Path $parent -Recurse | Where-Object {$_.PSIsContainer}
      $parent,$child
      

      【讨论】:

      • 我试过这个:$containers = $parent,$child,但是你得到的是 $containers = {upgrade},{in,out}——在那个,两个数组添加到 $containers .
      • 试试:$containers = $child+$parent
      • @ShayLevy 我认为这不会起作用,因为您正在尝试将数组添加到字符串中。但这应该: $containers = @($child)+$parent
      • @zdan 和 $child 或 $parent 都是字符串,都包含 DirectoryInfo 对象。你会得到不同的结果吗?
      猜你喜欢
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多