Help with Restoring ACLs in PowerShell: What’s Going Wrong?

0
0
Asked By TechWhiz101 On

I'm trying to back up and then restore the Access Control Entries (ACEs) for a directory in PowerShell, but I keep hitting an error during the restore process. The code I used for backing up is to recursively grab the ACL of the directory and export it to an XML file. After modifying some files, I'm attempting to restore the ACLs, but I'm getting an error. Here's a quick rundown of my code:

### Recursively backup the ACL of a directory
$Acl = Get-ChildItem -Path $TargetDirectory -Recurse | Get-ACL -ErrorAction Stop
$Acl | Export-Clixml -Path "$AclBackupFile"

### Restore the ACL
$RestoredAcl = Import-Clixml -Path $AclBackupFile
Set-Acl -Path $TargetDirectory -AclObject $RestoredAcl

The error I'm seeing states that there's an issue with the AclObject parameter. Any guidance on what I might be doing wrong?

4 Answers

Answered By CodeGuru99 On

It looks like you're trying to set the ACL for the top-level folder with a collection of ACLs, but that's not going to work. Each file and folder needs its security descriptor set individually if you're restoring like this. You may want to consider backing up only the files that need changes, and restore those after your modifications.

BackupBuff -

So, you can back up ACLs recursively but restoring them doesn't work the same way? That's a bummer. I'll try your suggestion. Thanks!

PowerShellPro -

You can restore the entire tree, but you need to pipe in $RestoredAcl to Set-Acl. This way, PowerShell can handle the paths correctly. It's more work for the CPU but easier to implement.

Answered By ScriptSavant76 On

That's a great approach! Focusing on the path baked into the object really helps streamline the process. Just make sure everything aligns right!

Answered By ScriptSavant76 On

You might want to try just passing $Acl instead of $RestoredAcl, unless I'm missing something here.

TechWhiz101 -

I just tested that out and it didn't work. I get what you were thinking though!

CodeGuru99 -

$Acl is a collection of ACLs since you used Get-ChildItem -Recurse, so that won't fix the error you're seeing.

Answered By PowerShellPal On

Set-Acl only accepts a single AclObject at a time, not a collection. Instead of using Set-Acl with -Path, you should pipe $RestoredAcl directly to Set-Acl like this:

$RestoredAcl | Set-Acl

This should resolve your issue since the $Acl object has the path included. You can verify with $RestoredAcl | Select Path to check.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.