Search code examples
powershellpowershell-4.0

Recursion depth in Powershell 4


I'm attempting to pull a small bit of information on subfolders within a given directory. I'm pretty new to powershell but after a week or so of stumbling about, I managed to put together this, which works perfectly for my purposes on Powershell 5. Trouble is, I need to make an equivalent script that will run in Powershell 4. The only thing that doesn't appear to work is the -Depth, which is a necessity.

$FolderPath = dir -Directory -Path "D:\FILEPATH\" -Recurse -Force -Depth 3
$Report = @()
Foreach ($Folder in $FolderPath) {
    $Acl = Get-Acl  -Path $Folder.FullName
    foreach ($Access in $acl.Access)
        {
        if (!($Access.IdentityReference -in $Exclude)) {
            $Properties = [ordered]@{
            'Folder and Location'=$Folder.FullName;
            'AD Group or User'=$Access.IdentityReference; 
            'Permissions'=$Access.FileSystemRights;
            'Inherited'=$Access.IsInherited}

            $Report += New-Object -TypeName PSObject -Property $Properties
        }
    }
}
$Report | Export-Csv -path "FILEPATH\Test.csv"

I've tried adding the "\*\**\***" and several variants therein to get the desired result but they either gave me from the 3rd subfolder down, or returned nothing. I've also looked into the Get-ChildItemToDepth setup but that appears to be restricted to functions only and I've no idea how to include that with what I have presently. Any guidance would be appreciated immensely!


Solution

  • What you can do is get a non-recursive list for each level, the root folder and then the three recursive levels that would have been included in -depth 3. You can run this on your PS5 machine, and check the $FolderPath.count against what you got using -Depth 3, and you should get the same count.

    $FolderPath = $(dir -Directory -Path "D:\FILEPATH\*" -Force
    dir -Directory -Path "D:\FILEPATH\*\*" -Force
    dir -Directory -Path "D:\FILEPATH\*\*\*" -Force
    dir -Directory -Path "D:\FILEPATH\*\*\*\*" -Force)