Search code examples
powershellloopsshortest-path

Powershell script to loop through directories, test if sub directory exists, then list all files on the location


I'm trying to recursively go through on all folders, looking for a specific sub folder (can be on multiple location), then list it's content (all files or even filter for specific extension).

For better understanding, let's assume that this is the directory tree:

tree view

So basically - following this example - I'd like to list all files under crypted folders (if it has any). Only crypted folders content (if possible, with specific extension like .txt). Including the path for better identification.

For example:

CUSTOMER1: IMPORTANT\CUSTOMER1\crypted\something1.txt IMPORTANT\CUSTOMER1\crypted\something2.txt CUSTOMER16: IMPORTANT\CUSTOMER16\crypted\something5.txt DEV2: IMPORTANT\DEV2\crypted\something1.txt TEMP1:

Do you have any idea, please?

Thanks!

I can manage to test-path and list files with this extension, but only with a given list of folders (stored in list.txt), where the script should be looped, but could not manage to have it without specifying the source.

$location = "C:\TEST\IMPORTANT"
$list = "C:\TEST\list.txt"

foreach($line in Get-Content $list) {
if ($line -match $regex) {
    
    $FolderExist = Test-Path "$location\$line\crypted"
if ($FolderExist -eq $True) {
    Write-Host "$line"
    Get-ChildItem "$location\$line\crypted" -Recurse -Include *.txt
    }
    else {
    Write-Host "$line does not have crypted folder"
}
}
}

Solution

  • There are a few steps which you need to follow in order to achieve your requirement:

    1. Get all crypted folders.
    2. Iterate through each crypted folder.
       2.1. Get the parent folder name.
       2.2. Get all the .txt files(or as requirement) in the 'crypted' folder.
       2.3. Output the files.
    

    Below is the script implementing above steps:

    $location = "C:\TEST\IMPORTANT"
    $folderName = "crypted"
    $extension = "*.txt"
    
    $cryptedFolders = Get-ChildItem -Path $location -Filter $folderName -Directory -Recurse
    
    foreach ($folder in $cryptedFolders) {
        $parentFolderName = $folder.Parent.Name
    
        $txtFiles = Get-ChildItem -Path $folder.FullName -Filter $extension -File
    
        Write-Host $parentFolderName":"
        foreach ($file in $txtFiles) {
            Write-Host $file.FullName
        }
    }
    # Outputs Name of folder: full path of file/s inside of crypted.
    # Sample: 
    # CUSTOMER1:
    # /home/runner/C/CUSTOMER1/crypted/something1.txt
    # /home/runner/C/CUSTOMER1/crypted/something2.txt
    

    SAMPLE DEMO