【问题标题】:Powershell for loopPowershell for 循环
【发布时间】:2015-06-01 14:03:35
【问题描述】:

我必须打印所有目录和所有文件。但是如果我找到一个目录,我必须“进入目录”并打印存储在该目录中的文件。它只有两层,第一层是完整的目录,第二层是文件。

我试过了,但是它没有进入目录,两次进入所有目录

$correcte = $args.Count
if ($correcte -lt 1){
    forEach ($item in (Get-ChildItem)){ //first level of directories
       if($item.PSIsContainer){
          forEach ($item in (Get-ChildItem)){               
             write-host $item //this should print the file inside the directory
          }
        }
    }
}
else{
    write-host "You don't have to pass any parameter"
}

【问题讨论】:

    标签: powershell directory get-childitem


    【解决方案1】:

    一旦确定它是一个目录,就需要在第二个循环中重新使用$item 变量。

    正如 Enrico 指出的,最好使用不同的变量名:

    $correcte = $args.Count
    if ($correcte -lt 1){
        forEach ($item in (Get-ChildItem)){ //first level of directories
           if($item.PSIsContainer){
              forEach ($subitem in (Get-ChildItem $item)){               
                 write-host $subitem.FullPath //this should print the file inside the directory
              }
            }
        }
    }
    else{
        write-host "You don't have to pass any parameter"
    }
    

    根据您的 powershell 版本,您可以通过首先获取目录来简化此操作:

    Get-ChildItem -Directory | % { gci $_ } 
    

    【讨论】:

      【解决方案2】:

      看起来Get-ChildItem 两次都在同一个文件夹中执行。在再次调用Get-ChildItem 之前,您需要“移动”到目标目录。

      附带说明,在内部循环中再次重用变量名称item 并不是一个好主意。很混乱。

      【讨论】:

        【解决方案3】:

        Get-Childitem 有一个 -recurse 参数可以做到这一点。如果您只想打印 gci 生成的项目,则以下内容就足够了:

        Get-Childitem -recurse
        

        【讨论】:

          猜你喜欢
          • 2020-01-27
          • 2018-12-21
          • 2018-08-21
          • 2018-07-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-13
          • 1970-01-01
          相关资源
          最近更新 更多