Issue with Try and Catch error handling. I broke the script. how to use it

Hello,
I was trying to add error handling to the script. So I added try and catch. however, it broke the script...See attached where I put try and catch. Below is a good script that is working without Try and catch. It makes a nice export of permissions. The script attached is where I added try and catch and it no longer works.

I would like to do error handling log for Directory and remote computer if they dont exist.

thank you so much

BELOW is WORKING script WITHOUT try and catch.


 Function Get-xACL {


    [CmdletBinding()]

    Param
    (
        [Parameter(Mandatory = $True)]
        [String[]$Group,
        [Parameter(Mandatory = $True)]
        [String[]$Directory,
        [Parameter(ValueFromPipelineByPropertyName = $True,
            ValueFromPipeline = $True)]
        [String[] $ComputerName = $env:COMPUTERNAME
    )

    Begin {
        $Report = @()
        Clear-Variable ACLs -ErrorAction SilentlyContinue
        New-EventLog –LogName Application –Source “Get-xAcl” -ErrorAction SilentlyContinue

        $DumpAcls = {
            param(
                $Directory,
                $Group
            )
           
            $DataToExport = @()
            $Dirs = @()

            Foreach ($d in $Directory) {
               
                if (Test-Path $d) {
                    $Dirs += $d -AS [System.IO.DirectoryInfo]
                    $Dirs += Get-ChildItem -Path $d -Recurse -Directory
                }
                else {
                    # possible directory didn't exist.  Write message to application log
                    #Write-EventLog -LogName Application -Source "Get-xACL" -EventId 2202 -EntryType Error -Message "unable to find directory: $d"
                }
            }

            Foreach ($dir in $Dirs) {
                $Acls = (Get-Acl -Path $dir.FullName).Access

                Foreach ($acl in $Acls) {
                    If ($acl.IdentityReference.Value.ToString() -in $Group) {
                        $props = @{
                            "Path"              = $dir.FullName
                            "IdentityReference" = $acl.IdentityReference.Value.ToString()
                            "AccessControlType" = $acl.AccessControlType
                            "InheritanceFlags"  = $acl.InheritanceFlags
                            "PropagationFlags"  = $acl.PropagationFlags
                            "FileSystemRights"  = $acl.FileSystemRights
                            "IsInherited"       = $acl.IsInherited
                        }

                        $DataToExport += (New-Object psobject -Property $props)

                    }# end if

                }# end foreach

            }# end foreach

            return $DataToExport

        }# end DumpAcls

    }# end Begin

    Process {
        Foreach ($Computer in $ComputerName) {
            If ($Computer -ne $env:COMPUTERNAME) {
                Write-Verbose "Remote Computer - $Computer"
                $ACLs = Invoke-Command -ComputerName $Computer -ScriptBlock $DumpAcls -ArgumentList $Directory, $Group
            }
            Else {
                Write-Verbose "Local computer - $Computer"
                $ACLs = Invoke-Command $DumpAcls -ArgumentList $Directory, $Group
            }

            $Report += $ACLs
        }
    }

    End {
        $Report | Export-Csv "c:\temp\NTFSPermissions.csv" -NoTypeInformation  
    }
}


   Get-xACL-WithTryAndCatch.txt
creative555Asked:
Who is Participating?
 
MichelangeloConsultantCommented:
As Jason wrote, you should pinpoint the command you want to catch instead of including many commands inside a try catch block.
Including lots of code does not allow you to intercept a given error.

Note: to intercept a non terminating error, add the switch
-Erroraction STOP 

Open in new window

to the command. This way, any error will be caught
0
 
Jason CrawfordTransport NinjaCommented:
First off, nice script :)

Try Catch will only catch terminating errors, and even then in my opinion you have already included enough error handling with the if ($computer -ne $env:computername) statement and including it inside a try/catch is overkill unless you're trying to catch an error with Invoke-Command in which case you should probably include it inside the catch block by itself.  Try/Catch/Finally was a hard concept for me to fully grasp due to the terminating error condition.  Play around with it a little more with less moving parts...that's what I had to do.
1
 
MichelangeloConsultantCommented:
I'm proposing my answer as best one as addresses original poster question. Jason Crawford's one does a good job in summarizing concepts in try/catch so it gets "assisted answer" mark.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.