下面的PowerShell脚本将列出所有共享文件夹(隐藏的共享文件夹除外),然后列出所有子文件夹,最后获取每个子文件夹的ACL信息并导出到CSV文件。
但是,我正在尝试设置它可以钻进的子文件夹的限制。例如,如果我将其设置为3,脚本将获取前三个子文件夹的ACL信息。我怎么能这样做?
输入:
path=\\server\sharefolder0\subfolder01\subfolder02
path=\\server\sharefolder1\subfolder11\subfolder12\subfolder13\subfolder14
path=\\server\sharefolder2
预期结果:
path=\\server\sharefolder0
path=\\server\sharefolder0\subfolder01
path=\\server\sharefolder0\subfolder01\subfolder02
path=\\server\sharefolder1
path=\\server\sharefolder1\subfolder11
path=\\server\sharefolder1\subfolder11\subfolder12
path=\\server\sharefolder2
这是代码:
$getSRVlist = Get-Content .\server.txt
$outputDirPath=".\DirPathList.txt"
$outputACLInfo=".\ACLInfo.CSV"
$header="FolderPath,IdentityReference,Rights"
Del $outputACLInfo
add-content -value $header -path $outputACLInfo
foreach ($readSRVlist in $getSRVlist)
{
foreach ($readShareInfoList in $getShareInfoList=Get-WmiObject Win32_Share
-computerName $readSRVlist | Where {$_.name -notlike "*$"} | %{$_.Name})
{
foreach ($readDirPathList in
$getDirPathList=get-childitem \\$readSRVlist\$readShareInfoList -recurse
| where {$_.PSIsContainer})# | %{$_.fullname})
{
$getACLList=get-ACL $readDirPathList.fullname | ForEach-Object
{$_.Access}
foreach ($readACLList in $getACLList)
{
$a = $readDirPathList.fullname + "," +
$readACLList.IdentityReference + "," + $readACLList.FileSystemRights
add-content -value $a -path $outputACLInfo
}
}
}
}
答案 0 :(得分:8)
递归是你的朋友。试试这个:
$maxDepth = 3
function TraverseFolders($folder, $remainingDepth) {
Get-ChildItem $folder | Where-Object { $_.PSIsContainer } | ForEach-Object {
if ($remainingDepth -gt 1) {
TraverseFolders $_.FullName ($remainingDepth - 1)
}
}
}
TraverseFolders "C:\BASE\PATH" $maxDepth
编辑:现在我明白了你的意思。要检查给定路径的前三个父文件夹,请尝试以下操作:
$server = "\\server\"
$path = ($args[0] -replace [regex]::escape($server), "").Split("\\")[0..2]
for ($i = 0; $i -lt $path.Length; $i++) {
Get-ACL ($server + [string]::join("\", $path[0..$i])
}
答案 1 :(得分:2)
在新版本的Powershell中,可以使用-DEPTH
参数,
一支班轮可以帮助您-
get-childitem -path \\server\folder -Depth 2 -Directory | Select-object -Property Name, Fullname
它将搜索2个嵌套文件夹,并将提供文件夹名称和该特定文件夹的完整路径。已在版本- PSVersion 5.1.17134.858
中进行了测试