'How to enable auditing on subfolders and files using powershell

I tried to enable the audit policy on folder using powershell script. But in my case the audit policy is not applied for subfolders and files within the folder which applied the audit policy.

I used the following code:

$TargetFolders = Get-Content C:\Input.txt
$AuditUser = "Everyone"
$AuditRules = "Delete,DeleteSubdirectoriesAndFiles,ChangePermissions,Takeownership"
$InheritType = "ContainerInherit,ObjectInherit"
$AuditType = "Success"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAuditRule($AuditUser,$AuditRules,$InheritType,"None",$AuditType)
foreach ($TargetFolder in $TargetFolders)
{
    $ACL = Get-Acl $TargetFolder
    $ACL.SetAuditRule($AccessRule)
    Write-Host "Processing >",$TargetFolder
    $ACL | Set-Acl $TargetFolder
}
Write-Host "Audit Policy applied successfully."

In Advanced security setting prompt prompt it also shows that

“apply onto: ‘this folder,subfolder and files.'”

but audit policy is not applied for the subfolders and files. when i tick on the following tick box.

“Replace all existing inheritable auditing entries on all descendants with inheritable auditing entries from this object”

then it's applied on subfolders and files within it.

So how can I tick on this programatically (using powershell)?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source