Meet101
Meet101

Reputation: 801

Reach to specific folder without knowing the full path in PowerShell

I want to find sub-folder inside the main folder.

Example like I have a folder called build and inside build there are sub-folders as an example XYZ, Inside XYZ there are other sub-folders like ZYX, Inside it there are other folders. full path like : build\XYZ\ZYX\ABC.

I want to go to ABC but, I don't have a path to reach it. How to find sub-folder and go to it in PowerShell script. Will Get-childItem work? If yes, how?

Upvotes: 2

Views: 2308

Answers (3)

Adil Hindistan
Adil Hindistan

Reputation: 6605

This might be a bit long winded but I guess you are trying to first find out the longest path (deepest in the hierarchy) to cd to it, so maybe something like this:

Set-Location (Get-ChildItem 'c:\CICDTestCICD' -Recurse -Directory |% { 
               [PSCustomObject]@{Path=$_.FullName; 
                                 Depth=($_.fullname.split('\')).count 
                                } 
                                                                     } | 
             sort Depth -Descending | select -first 1
            ).path

The idea is that:

  • you split full path name using '\' as a separator for each directory;
  • create a PSCustomObject to hold the Full Path and Depth of Directory for each
  • Sort by the depth and select the deepest path in the hierarchy
  • Print the full path and change directory to that

Upvotes: 1

SavindraSingh
SavindraSingh

Reputation: 961

You can use the -Directory switch and search recursively using below command:

Get-ChildItem *ABC* -Recurse -Directory

Where *ABC * is the part of the name of the folder that you are trying to find.

Upvotes: 2

Martin Brandl
Martin Brandl

Reputation: 58931

You can use the Get-ChildItem cmdlet to retrieve all directories and use the Where-Object cmdlet to exclude all folder which has sub directories:

Get-ChildItem 'your_path_to_build' -Recurse -Directory | Where-Object { ![IO.Directory]::GetDirectories($_.FullName) }

Upvotes: 2

Related Questions