PowerShell 获取文件夹所有者 3 个文件夹深度

PowerShell to get Folder Owner 3 Folders Deep

我需要获取共享网络驱动器上所有文件夹所有者的列表。但是,我想将递归限制为仅 3 个文件夹深度(尽管我们告诉他们不要这样做,但我们的一些用户会创建几个深度的文件夹)。我找到了下面的脚本,并将其稍微修改为仅提供文件夹所有者(它最初 return 编辑了很多关于 ACL 的信息),但它仍然会遍历每个文件夹级别。我怎样才能将其修改为仅 return 3 个文件夹级别?

$OutFile = "C:\temp\FolderOwner.csv" # indicates where to input your logfile#
$Header = "Folder Path;Owner"
Add-Content -Value $Header -Path $OutFile 

$RootPath = "G:\" # which directory/folder you would like to extract the acl permissions#

$Folders = dir $RootPath -recurse | where {$_.psiscontainer -eq $true}

foreach ($Folder in $Folders){
    $Owner = (get-acl $Folder.fullname).owner
    Foreach ($ACL in $Owner){
    $OutInfo = $Folder.Fullname + ";" + $owner
    Add-Content -Value $OutInfo -Path $OutFile
    }
}

您应该可以在每个级别的路径中添加“*”。例如,这应该 return 项目在 C:\Temp:

下的三层深处
dir c:\temp\*\*\*

这是您可以使用的示例函数(它是为 PowerShell v3 或更高版本编写的,但可以修改为适用于版本 2):

function Get-FolderOwner {
    param(
        [string] $Path = "."
    )

    Get-ChildItem $Path -Directory | ForEach-Object {
        # Get-Acl throws terminating errors, so we need to wrap it in
        # a ForEach-Object block; included -ErrorAction Stop out of habit
        try {
            $Owner = $_ | Get-Acl -ErrorAction Stop | select -exp Owner
        }
        catch {
            $Owner = "Error: {0}" -f $_.Exception.Message
        }

        [PSCustomObject] @{
            Path = $_.FullName
            Owner = $Owner
        }
    }
}

那么你可以这样使用它:

Get-FolderOwner c:\temp\*\*\* | Export-Csv C:\temp\FolderOwner.csv

如果你在所有项目之后达到并包括 3 层深,你可以像这样修改函数:

function Get-FolderOwner {
    param(
        [string] $Path = ".",
        [int] $RecurseDepth = 1
    )

    $RecurseDepth--

    Get-ChildItem $Path -Directory | ForEach-Object {
        # Get-Acl throws terminating errors, so we need to wrap it in
        # a ForEach-Object block; included -ErrorAction Stop out of habit
        try {
            $Owner = $_ | Get-Acl -ErrorAction Stop | select -exp Owner
        }
        catch {
            $Owner = "Error: {0}" -f $_.Exception.Message
        }

        [PSCustomObject] @{
            Path = $_.FullName
            Owner = $Owner
        }

        if ($RecurseDepth -gt 0) {
            Get-FolderOwner -Path $_.FullName -RecurseDepth $RecurseDepth
        }
    }
}

并像这样使用它:

Get-FolderOwner c:\temp -RecurseDepth 3 | Export-Csv C:\temp\FolderOwner.csv

有什么帮助吗?

resolve-path $RootPath\*\* |
 where { (Get-Item $_).PSIsContainer } -PipelineVariable Path |
 Get-Acl |
 Select @{l='Folder';e={$Path}},Owner