Link to home
Start Free TrialLog in
Avatar of tilbard
tilbardFlag for United States of America

asked on

Powershell error handling

I have a script that lists the directories in a specific location, then goes through and sets the ACLs on them (using get-acl and set-acl). Basically, it takes the name of the folder, which happens to be the name of the user who owns the folder (Home Directories), and gives them modify permissions and sets the folder to inherit from the root folder.

However, when running the script, it errors out when it comes to a folder for which there is no matching user (in the case of terminated employees). I'm looking for a way to ignore that folder and simply move on. The "-ea silentlycontinue" parameter won't work unfortunately, as it's not actually a cmdlet that's erroring out. Attached is the code, and any help is appreciated!

I know I could write some code that would check if the user exists in AD before attempting to modify the ACL, but we're only talking about 3-4 out of ~2000, so that seems kind of like overkill at this point. If that's the best solution though, I'll go with that.

It errors out on the 3rd to last line, $ACLBase.SetAccessRule($AccessRule).
cls
Set-Location d:\Data\Home
$Inherit = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$propogation = [System.Security.AccessControl.PropagationFlags]"None"
$Foldername = Get-ChildItem * | Where-Object {$_.attributes -match "Directory"}
 
foreach ($Fullpath in $Foldername) {
$ACLBase = Get-Acl d:\Data\Home\
#Uncomment the following line to verify default permissions during step debugging
#Set-Acl -Path $Fullpath -AclObject $ACLBase
$username = $Fullpath.Name
$AddACL = "advocatesinc\$username", "Modify", $Inherit, $propogation, "Allow"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $AddACL
$ACLBase.SetAccessRule($AccessRule)
$ACLBase | Set-Acl $Fullpath 
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Chris Dent
Chris Dent
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tilbard

ASKER

Thanks again, that's twice today now! Catching the exception with Trap worked, though just ignoring it by setting the ErrorActionPreference still errored out the script.