powershellget-childitempester-5

get-childitem either subfolder or a "rbac.jsonc" file


I want to check if all folders contains either a subfolder or an rbac.jsonc file.

is this somehow possible ?


Solution

  • Your question lack some clarity for me as it stand.

    Based on your post, what I understand is:

    Please update your question with additional details or clarify the situation if I didn't get the premise right.

    In any case, what you seek to do is possible but not through a single Get-ChildItem statement.

    The way I'd go about it, since you want a recurse operation with multiple checks that stop processing a folder once it has been validated, is an home-made -recurse done through a single-layer Get-ChildItem alongside a queue where the recursion is done "manually", one layer at a time within a while loop that persist until the queue is cleared out.

    $topMgFolderPath = 'C:\temp\'
    
    $queue = [System.Collections.Queue]::new()
    $InvalidFolders = [System.Collections.Generic.List[PSobject]]::new()
    $Directories = Get-ChildItem -path $topMgFolderPath  -Exclude '.policy' -Directory
    $Directories | % { $queue.Enqueue($_.FullName) }
    
    
    while ($Queue.Count -gt 0) {
        $dir = $queue.Dequeue()
        $HasRbacFile = Test-Path -Path "$dir\rbac.json"
        # If Rbac file exist, we stop processing this item
        if ($HasRbacFile) { Continue }
    
        $SubDirectories = Get-ChildItem -Path $dir -Directory -Exclude '.policy'
        # If the rbac file was not found and no subfolders exist, then it is invalid
        if ($SubDirectories.count -eq 0) {
            $InvalidFolders.Add($dir)
        } else {
            # Subdirectories found are enqueued so we can check them 
            $SubDirectories | % {$queue.Enqueue($_.FullName)}
        }
    
    }
    # Based on your second line of code where you performed that validation.
    $InvalidFolders | should -BeNullOrEmpty
    

    Everything important happens in the while loop where the main logic

    References

    Queue Class