我正在尝试编写一个递归函数,它将返回数组中的信息,但是当我将 return 语句放入函数中时,它会丢失某些条目。
我试图递归地查看指定深度的文件夹,获取与该文件夹关联的 acl。我知道 getChildItem 有一个递归选项,但我只想单步执行 3 层文件夹。
下面的代码摘录是我一直用于测试的代码。当调用 getACLS 而不使用 return 语句(下面注释掉)时,结果为:
Folder 1
文件夹12
文件夹13
Folder 2
当使用 return 语句时,我得到以下输出:
Folder 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)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)