带返回的Powershell递归

Rum*_*ser 5 powershell recursion return function

我正在尝试编写一个递归函数,它将返回数组中的信息,但是当我将一个return语句放入函数时,它会错过某些条目.

我试图以递归方式查看指定深度的文件夹,以获取与文件夹关联的acl.我知道getChildItem有一个递归选项,但我只想逐步浏览3个级别的文件夹.

以下代码的摘录是我一直用于测试的.如果在没有return语句的情况下调用getACLS(在下面注释掉),结果是:

文件夹1

文件夹12

文件夹13

文件夹2

当使用return语句时,我得到以下输出:

文件夹1

文件夹12

所以看起来return语句是从递归循环中退出的?

我的想法是,我想返回一个多维数组,如[文件夹名称,[acls],[[子文件夹,[权限],[[...]]]]]等.

cls

function getACLS ([string]$path, [int]$max, [int]$current) {

    $dirs = Get-ChildItem -Path $path | Where { $_.psIsContainer }
    $acls = Get-Acl -Path $path
    $security = @()

    foreach ($acl in $acls.Access) {
        $security += ($acl.IdentityReference, $acl.FileSystemRights)
    }   

    if ($current -le $max) {
        if ($dirs) {
            foreach ($dir in $dirs) {
                $newPath = $path + '\' + $dir.Name
                Write-Host $dir.Name
   #            return ($newPath, $security, getACLS $newPath $max ($current+1))
   #            getACLS $newPath $max ($current+1)
                return getACLS $newPath $max ($current+1)
            }   
        }
    } elseif ($current -eq $max ) {
        Write-Host max
        return ($path, $security)
    }
}

$results = getACLS "PATH\Testing" 2 0
Run Code Online (Sandbox Code Playgroud)

Rum*_*ser 8

问题是回归的位置.我把它放在foreach循环中,这意味着它试图在一个函数中多次返回.我把它移到foreach之外,改为if语句.

function getACLS ([string]$path, [int]$max, [int]$current) {

$dirs = Get-ChildItem -Path $path | Where { $_.psIsContainer }
$acls = Get-Acl -Path $path
$security = @()
$results = @()

foreach ($acl in $acls.Access) {
    $security += ($acl.IdentityReference, $acl.FileSystemRights)
}   

if ($current -lt $max) {
    if ($dirs) {
        foreach ($dir in $dirs) {
            $newPath = $path + '\' + $dir.Name
            $next = $current + 1
            $results += (getACLS $newPath $max $next)
        }   
    } else {
        $results = ($path, $security)
    }
    return ($path, $security, $results)
} elseif ($current -eq $max ) {
    return ($path, $security)
}
}
Run Code Online (Sandbox Code Playgroud)