Set Auditing on System Files and Folders with PowerShell

It's easy to set auditing on files and folders using GUI. But imagine if you need to perform this operation on hundreds of servers. PowerShell is your friend in this case!
This article discusses specifics of applying auditing changes on system files and folders (e.g.: C:\Windows, C:\windows\system32\winload.exe). Usually local admin has no write access for these files.

Standard approach of using Set-Acl cmdlet is not working with system files or folders. You might get  UnauthorizedAccessException and you'll see an error: "Set-Acl : Attempted to perform an unauthorized operation." This bug has been reported to Microsoft, but still not fixed.
In the meantime for such cases I created the following function:
function Set-AuditFail
# Enable Auditing on the file or folder, with the following specifications. Name: Everyone; Access: Failed for all listed accesses
 {
   param([String]$TargetFolder)
   $ACL = Get-Acl -Path $TargetFolder -Audit
   If (($ACL.AuditToString -eq "Everyone Failure  FullControl") -OR ($ACL.AuditToString -eq "Everyone Failure  DeleteSubdirectoriesAndFiles, Modify, ChangePermissions, TakeOwnership")){
        Return "Audit settings for object $TargetFolder are correct"
    }
    Else{
        Write-Output "Audit settings for object $TargetFolder are wrong. Modifying..."
        $ACL = [IO.File]::GetAccessControl($TargetFolder, "Audit")
        $rule = New-Object System.Security.AccessControl.FileSystemAuditRule("Everyone","Fullcontrol","None","None","Failure")
        $ACL.SetAuditRule($rule)
        [IO.File]::SetAccessControl($TargetFolder, $ACL)
    }
}
This function uses direct access to .NET Framework class IO.File and apparently this class doesn't have the mentioned bug.

Disclaimer: All posts and opinions on this site are provided AS IS with no warranties. These are my own personal opinions and do not represent my employer’s view in any way.

Comments

Popular posts from this blog

How to uninstall a broken software

Xerox 116-324 fault when printing .doc or .pdf containing callibri fonts

Create Outlook calendar item with Python