PowerShell让文件夹所有者3文件夹深入

时间:2015-01-26 16:11:47

标签: powershell permissions acl powershell-v3.0 directory

我需要获取共享网络驱动器上所有文件夹所有者的列表。但是,我想将递归限制在3个文件夹深处(我们的一些用户会创建几个级别的文件夹,尽管我们告诉他们不要)。我找到了下面的脚本,并略微修改它只是给文件夹所有者(它最初返回了更多的ACL信息),但它仍然在每个文件夹级别下降。如何将其修改为仅返回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
    }
}

2 个答案:

答案 0 :(得分:0)

您应该可以添加' *'到每个级别的路径。例如,这应该在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

答案 1 :(得分:0)

任何帮助?

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