Wednesday, August 26, 2015

Recursive search for folder with Powershell

Recently I needed to solve a fairly trivial task - recursively find folder by name using Powershell. As a result, I’ve wrote function:

 

function FindFolder($rootDir, $dirToFind)

{

  if ((Get-ChildItem $rootDir $dirToFind).count -eq 1)

  {

    return $rootDir

  }

 

  $directories = Get-ChildItem $rootDir | ?{ $_.PSIsContainer } | sort LastWriteTime -Descending

 

  foreach($directory in $directories)

  {

    $dirName = $rootDir + $directory.Name + "\"

    if ((Get-ChildItem $dirName $dirToFind).count -eq 1)

    {

      return $dirName + $dirToFind

    }

    if ((Get-ChildItem $dirName).count -gt 0)

    {

      $ret = FindFolder $dirName $dirToFind

      if ($ret -ne "")

      {

        return $ret

      }

    }

  }

 

  return ""

}

 

 

Arguments for function are root directory where it will start searching and name of the folder. Function returns the full path to the first found folder - that's exactly what I needed. If you want to get all possible folders, you can edit the script, and for example, echo each found folder and then parse the result. Just keep in mind that I’m sorting results inside function by the last write time because I need to find newest of all possible folders with this name (sort LastWriteTime -Descending).

 

No comments:

Post a Comment