2021-01-15

Backup and Restore NTFS Permission (ACL) and Owner with PowerShell

Backup

$TargetPath = 'C:\PathToBackup';
$ACLFile = 'C:\NTFSBackup.csv';
$PathReplaceKeyword = 'AKeywordToReplacePathForRetoreToDifferentPath'

$ACLArray = @();
$ACLArray += (Get-item -path $TargetPath | Get-ACL | Select-Object @{Name="Path"; Expression={($_.Path -Replace [regex]::Escape($TargetPath),$PathReplaceKeyword)}},Owner,Sddl);
$ACLArray += (Get-Childitem -path $TargetPath -recurse | Get-ACL | Select-Object @{Name="Path"; Expression={($_.Path -Replace [regex]::Escape($TargetPath),$PathReplaceKeyword)}},Owner,Sddl);
$ACLArray | Export-CSV $ACLFile -NoTypeInformation;

 

Restore

$TargetPath = 'C:\PathToRestore';
$ACLFile = 'C:\NTFSBackup.csv';
$PathReplaceKeyword = 'AKeywordToReplacePathForRetoreToDifferentPath';

$ACLArray = Import-Csv -Path $ACLFile;
foreach ( $ACLRecord in $ACLArray ) {
$ACLRecord.Path = ($ACLRecord.Path -Replace $PathReplaceKeyword,$TargetPath);
$ACL = Get-Acl $ACLRecord.Path;
$ACL.SetSecurityDescriptorSddlForm($ACLRecord.Sddl);
$ACL.SetOwner((New-Object System.Security.Principal.NTAccount($ACLRecord.Owner)));
$ACL | Set-Acl $ACLRecord.Path;
};


沒有留言:

張貼留言