troubleshooting Question

Finally called even if catch has a return statement

Avatar of David Sankovsky
David SankovskyFlag for Israel asked on
Active DirectoryScripting LanguagesPowershell
4 Comments2 Solutions15 ViewsLast Modified:

Hi Guys,

I'm building a PS script to export users who leave the company,

Since it's a fairly comlicated and has many stages, to follow them, I decided to wrap each step in a try catch system.

unless I misunderstand something, in a try catch syntac, the finally is only called when non of the catch do (as in when the script runs properly)

however the following code which was build intentionally to fail (there's no such user) return true:

function retry
{     $exsuccess     try      {         $SGExportPath = "\\sharename\exports\SecGroups\"         $usr = Get-ADUser davidsa         $sgpath = $SGExportPath+$((Get-ADUser -Properties * davidsa).SamAccountName)+".csv"         Get-ADPrincipalGroupMembership -Identity davidsa | Where-Object {($_.GroupCategory -eq "Security") -and ($_.Name -notlike "*ReportingGroup*")} |select Name,objectGUID |Export-Csv -Path $($SGExportPath+$((Get-ADUser -Properties * davidsa).samaccountname)+".csv") -NoTypeInformation -Encoding UTF8         Set-ADObject $usr -add @{extensionattribute14 = "SG Exported"}         Set-ADObject $usr -add @{extensionattribute15 = $sgpath}           }     catch     {         $exsuccess = $false         write-host $_         return $false     }     finally     {         $exsuccess = $true     }     return $exsuccess } if (retry) {     write-host "Success" } else {     Write-Host "fail" }

When I run the script I get the following result:

Cannot find an object with identity: 'davidsa' under: 'DC=moin,DC=gov,DC=il'.

So on one hand, it caught the write-host $_ section in the catch, but the function still returned true.

what am I missing?

Join our community to see this answer!
Unlock 2 Answers and 4 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros