ファイルサーバのアクセス権調査

$root = "D:\"
$outputDir = "C:\Temp"

# ============================================================
# 1. NTFSアクセス権取得
#    D:\ + 1階層目 + 2階層目 + 3階層目 + 4階層目
# ============================================================

$folders = @(
    Get-Item $root
)

# 1階層目
$level1 = Get-ChildItem $root -Directory -Force -ErrorAction SilentlyContinue |
    Where-Object {
        $_.Name -notin @(
            'System Volume Information',
            '$RECYCLE.BIN'
        )
    }
$folders += $level1

# 2階層目
$level2 = $level1 | ForEach-Object {
    Get-ChildItem $_.FullName -Directory -Force -ErrorAction SilentlyContinue
}
$folders += $level2

# 3階層目
$level3 = $level2 | ForEach-Object {
    Get-ChildItem $_.FullName -Directory -Force -ErrorAction SilentlyContinue
}
$folders += $level3

# 4階層目
$level4 = $level3 | ForEach-Object {
    Get-ChildItem $_.FullName -Directory -Force -ErrorAction SilentlyContinue
}
$folders += $level4

$folders | ForEach-Object {

    $path = $_.FullName

    try {
        (Get-Acl $path -ErrorAction Stop).Access |
            Select-Object `
                @{Name="Path"; Expression={$path}},
                IdentityReference,
                AccessControlType,
                FileSystemRights,
                IsInherited,
                InheritanceFlags,
                PropagationFlags
    }
    catch {
        Write-Warning "ACL取得失敗: $path"
    }

} | Export-Csv `
    "$outputDir\ACL_NTFS_DriveD_4Level.csv" `
    -NoTypeInformation `
    -Encoding UTF8


# ============================================================
# 2. Dドライブ上の共有フォルダと共有アクセス権取得
# ============================================================

Get-SmbShare |
    Where-Object {
        $_.Path -and
        $_.Path.StartsWith("D:\")
    } |
    ForEach-Object {

        $share = $_

        try {
            Get-SmbShareAccess -Name $share.Name -ErrorAction Stop |
                Select-Object `
                    @{Name="ShareName"; Expression={$share.Name}},
                    @{Name="Path"; Expression={$share.Path}},
                    AccountName,
                    AccessControlType,
                    AccessRight
        }
        catch {
            Write-Warning "共有アクセス権取得失敗: $($share.Name)"
        }

    } | Export-Csv `
        "$outputDir\ACL_Share_DriveD.csv" `
        -NoTypeInformation `
        -Encoding UTF8