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



我需要获取共享网络驱动器上所有文件夹所有者的列表。但是,我想将递归限制为仅 3 个文件夹深(我们的一些用户会创建几级深的文件夹,尽管我们告诉他们不要这样做)。我找到了下面的脚本,并对其进行了轻微修改以仅提供文件夹所有者(它最初为 ACL 返回了更多信息),但它仍然在每个文件夹级别下降。如何修改它以仅返回 3 个文件夹级别?

$OutFile = "C:tempFolderOwner.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
    }
}

您应该能够在每个级别的路径中添加"*"。例如,这应该返回 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:tempFolderOwner.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:tempFolderOwner.csv

有什么帮助吗?

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

最新更新