Thursday, 10 December 2015

Compare File Permission with powershell instead of calcs , xcacls, Icacls

The following Powershershell is handy, it will compare 2 directories ACLs and report any differences.

#CompareNetworkACL.ps1
[System.IO.FileInfo] $outputFile = "C:\temp\AclCompareDump.txt"
[System.IO.DirectoryInfo] $searchDirSource = Read-Host -Prompt "Enter source project folder path to search"
[System.IO.DirectoryInfo] $searchDirTarget = Read-Host -Prompt "Enter target project folder path to search"

if ($outputFile.Exists)
{
    $outputFile.Delete()
}

if ($searchDirSource.Exists -and $searchDirTarget.Exists)
{
   foreach ( $sourceProject in $( Get-ChildItem $searchDirSource | where { $_.psIsContainer -eq $true } ) ) {
        $targetProject = Get-Item $($searchDirTarget.FullName + "\" + $sourceProject.Name)

        foreach ( $sourceArea in $( Get-ChildItem $sourceProject.FullName | where { $_.psIsContainer -eq $true } ) ) {
            $targetArea = Get-Item $($targetProject.FullName + "\" + $sourceArea.Name)

            foreach ($sourceTaskFolder in $($sourceArea | Get-ChildItem | where { $_.psIsContainer -eq $true }) ){
                $targetTaskFolder = Get-Item $($targetArea.FullName + "\" + $sourceTaskFolder.Name)

                $currentAcl = Get-Acl $sourceTaskFolder.FullName
                $refacl = Get-Acl $targetTaskFolder.Fullname

                Write-Progress -Activity "Searching source for folder ACLs..." -Status ("Comparing " + $sourceTaskFolder.FullName + " to " + $targetTaskFolder.FullName)

                $comparison = compare-object $refacl $currentAcl -Property Access
                if ($comparison -ne $null)
                {
                    $sourceTaskFolder.Fullname | Out-File $outputFile.FullName -Append
                    [int] $hits += 1
                }
                $comparison = $null
            }
        }
    }

    if ($hits)
    {
        & notepad.exe $outputFile.Fullname
    }
    else
    {
        Write-Warning "All target ACLs matched the source ACLs."
    }
}

No comments:

Post a Comment