Powershell查询给定的目录层 1


支持PS3.0以后

当你使用Get-Ghilditem去列出文件夹的内容时,你可以添加一个-Recurse参数去获取里面的子目录。然而,这不能让你控制其嵌套层数。GC将查询整个子目录,而不会关心它是否有很多嵌套层。

Get-ChildItem -Path $env:windir -Filter *.log -Recurse -ErrorAction SilentlyContinue

有时,你可以看到这种限制嵌套层数的方案:

Get-ChildItem -Path $env:windir\*\*\* -Filter *.log -ErrorAction SilentlyContinue

然而,这不是限制嵌套三层范围,而是查询全部的第三层目录。下面这个则不会,例如获取一、二层目录所有内容。

限制嵌套的层数唯一的方式就是递归自己:

function Get-MyChildItem
{
  param
  (
    [Parameter(Mandatory = $true)]
    $Path,
    
    $Filter = '*',
    
    [System.Int32]
    $MaxDepth = 3,
    
    [System.Int32]
    $Depth = 0
  )
  
  $Depth++

  Get-ChildItem -Path $Path -Filter $Filter -File 
  
  if ($Depth -le $MaxDepth)
  {
    Get-ChildItem -Path $Path -Directory |
      ForEach-Object { Get-MyChildItem -Path $_.FullName -Filter $Filter -Depth $Depth -MaxDepth $MaxDepth}
  }
  
}

Get-MyChildItem -Path c:\windows -Filter *.log -MaxDepth 2 -ErrorAction SilentlyContinue |
  Select-Object -ExpandProperty FullName

本次执行将从WINDOWS目录及其2层内得到全部的*.log文件。

原文地址:Recursing a Given Depth

本文链接: https://www.pstips.net/recursing-a-given-depth.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

一条评论 “Powershell查询给定的目录层