Remove orphaned SIDs from File/Folder ACL (PowerShell)

Introduction

This script is used to remove orphaned SIDs from File/Folder ACL.

Scenarios

Sometimes, the objects are removed, but the orphaned SIDs are remained​ under security tab. The orphaned SIDs are annoying.

Script

This script contains one  advanced function, Remove-OSCSID , You can use this script in the following ways:
Method 1:
  1. Download the script and open the script file with Notepad or any other script editors.
  2. Scroll down to the end of the script file, and then add the example command which you want to run.
  3. Save the file then run the script in PowerShell.
Method 2:
      1. Rename scriptname.ps1 to scriptname.psm1 (PowerShell Module file)
      2. Run Import-Module cmdlet to import this module file.
        Import-Module filepath\scriptname.psm1

Examples

 Example 01: Remove orphaned SIDs from one file /folder 
 Command:   Remove-OSCSID   -path   C:\acls.txt
 Screenshot:
 Before the command executed:   
 After the command executed:
Example 02: Remove orphaned SIDs from all the files/folders  ACL of  the  path
Command:   Remove-OSCSID  -Path c:\test  -recurse
Screenshot:
Note:  This command  Remove-OSCSID  -Recurse  will remove all  orphaned SIDs from the childitems ACL  of the specified folder. If the path is one file, it will do nothing.
 
Here are some code snippets for your references. To get the complete script sample, please click the download button at the beginning of this page.
PowerShell
Edit|Remove
$acl = Get-Acl-Path $Pathforeach($accin$acl.access ) 
{ 
    $value = $acc.IdentityReference.Value 
    if($value-match "S-1-5-*") 
    { 
        $ACL.RemoveAccessRule($acc|Out-NullSet-Acl-Path $Path-AclObject $acl-ErrorAction Stop 
        Write-Host "Remove SID: $value  form  $Path " 
    } 
}

Prerequisite

Windows PowerShell 2.0
Windows Server 2008R2
Additional Resources
Technical Resource: 
Get-ACL
Set-ACL