Link to home
Start Free TrialLog in
Avatar of David Sankovsky
David SankovskyFlag for Israel

asked on

Finally called even if catch has a return statement

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" }

Open in new window


When I run the script I get the following result:

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

Open in new window

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

what am I missing?

SOLUTION
Avatar of Michael Pfister
Michael Pfister
Flag of Germany 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
the finally section will always be called. we use it to dispose any objects.
ASKER CERTIFIED SOLUTION
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
Off topic, but I prefer the Allman style over OTBS for readability,  But I've also encountered where pasting code using the Allman style, which works just fine in a script, into a console is not interpreted correctly (detected as syntax errors), whereas using OTBS just works.  In the end, I pretty much use the Allman style with some variation, but just remain consistent about it.