function - 带返回的Powershell递归

标签 function powershell recursion return

我试图编写一个将在数组中返回信息的递归函数,但是当我将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

最佳答案

问题是退货地点。我将它放在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)
}
}

关于function - 带返回的Powershell递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4989021/

相关文章:

powershell - PowerShell 中使用命名空间的范围是什么?

c# - .NET 应用程序将不同的操作系统版本返回到 Windows 10 上的 PowerShell

php - 定期将分隔符插入字符串

MySQL压平2个连接的递归表

c++ - 将二维数组传递给函数以更改值

javascript - JS : "this" in function context in strict mode, MDN 规范与 chrome 67 实现不匹配

java - Scala lambdas 实现与 Java 8

C 递归函数

maven - 如何在maven中运行powershell脚本

java - 排列、递归