如何使用PowerShell遍历驱动器中的所有目录

时间:2016-05-17 13:31:49

标签: powershell powershell-v2.0

我有以下powershell脚本,它给了我一个特定文件夹的权限。

在下面的脚本中,例如,我可以获取名为SP的目录的每个文件夹(包括子文件夹)的权限,

如何遍历所有文件夹而不是特定的targetDirectory?

$targetServer    = '\\tst-server\f$\'    #Enter hostname
$targetDirectory = 'SP' #Enter directory name
$target          = Join-Path -ChildPath $targetDirectory -Path $targetServer
$arrResults      = @() #Initialize array used to store custom object output
$exportPath      = 'C:\Users\adt\Desktop\Scripts\output\FolderPermission.csv' #Enter name of the CSV output file

#Query target directory for all 'folders' (excludes files via Where statement)
Get-ChildItem -Recurse -Path $target | Where { $_.PSIsContainer } |
forEach {
    $objPath = $_.FullName
    $coLACL  = Get-Acl -Path $objPath
    forEach ( $objACL in $colACL ) {
        forEach ( $accessRight in $objACL.Access ) {
            $objResults = New-Object –TypeName PSObject
            $objResults | Add-Member –MemberType NoteProperty –Name DirectoryPath      –Value $objPath
            $objResults | Add-Member –MemberType NoteProperty –Name Identity           –Value $accessRight.IdentityReference
            $objResults | Add-Member –MemberType NoteProperty –Name SystemRights       –Value $accessRight.FileSystemRights
            $objResults | Add-Member –MemberType NoteProperty –Name SystemRightsType   –Value $accessRight.AccessControlType
            $objResults | Add-Member -MemberType NoteProperty -Name IsInherited        -Value $accessRight.IsInherited
            $objResults | Add-Member -MemberType NoteProperty -Name InheritanceFlags   -Value $accessRight.InheritanceFlags
            $objResults | Add-Member –MemberType NoteProperty –Name RulesProtected     –Value $objACL.AreAccessRulesProtected
            $arrResults += $objResults
        }
    }
}

$arrResults | Export-CSV -NoTypeInformation -Path $exportPath

1 个答案:

答案 0 :(得分:1)

您只需将Path设置为F:

即可
Get-ChildItem F: -Recurse | Where { $_.PSIsContainer } | Foreach-Object { 
   #do something 
}