Search code examples
powershellforeacherror-handlingfile-permissionsadgroup

Catching errors within powershell script


I have written a script to pull permissions from file directories so that we can audit access to folders. I just want to see what groups we have not what users so I wrote this script to pull out all group names and remove the domain name from the value so that it can then run it through a second script that corrects the AD group name for us if its incorrect at all since we ran into an issue where for some reason some were coming back with slightly different names. The problem is all the AD users named in permissions come back as errors. I want those errors to not even show up on screen is there a way to do that? As you can see I have been trying a few different ways to pipe them to a log or the -ea ignore option but it still shows the errors on screen.

$filelocationscsv = "C:\AD\Excel\File Share migration.csv"
$filelocationcsvcontents = Get-Content -LiteralPath $filelocationscsv

$AllFolders = @()
foreach ($location in $filelocationcsvcontents) {
    $AllFolders += $location.Substring(0,$location.Length-1)
}

$outputfilelocation = "C:\AD\Excel\permissions.csv"

$Results = @()
$errResults = @()
Foreach ($i in $Allfolders) {
    if (Test-Path $i){
    Write-Host "Obtaining file permissions for $i."
    $acl = (Get-Acl $i -Filter *).Access | select -ExpandProperty IdentityReference
    foreach($Access in $acl) {
    if ($Access.Value -notlike "BUILTIN\Administrators" -and $Access.Value -notlike "domain\Domain Admins" -and $Access.Value -notlike "CREATOR OWNER" -and $access.Value -notlike "NT AUTHORITY\SYSTEM" -and $access.Value -notlike "Everyone" -and $access.Value -notlike "BUILTIN\Users" -and $access.Value -notlike "s-1*") {
    [string]$perm = $Access.Value.Split('\')[1]
      if($checkgroup = Get-ADGroup $perm){
#try
#{
##                if( $LASTEXITCODE -gt 0 ){
##                # Handle the error here
##                # This example writes to the error stream and throws a terminating error
##                $errResults += $LASTEXITCODE
##                Write-Error "Unable to ping server, ping returned" -EA Ignore
##                }
                $Properties = [ordered]@{'AD Group'=$perm}
                $Results += New-Object -TypeName PSObject -Property $Properties
#}
#Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
#{
#                Write-Verbose "$perm skipped." -Verbose
#                #$ErrorMessage = 
#                #$FailedItem = $_.Exception.ItemName
#                #$errResults += $ErrorMessage + $FailedItem
#}
                }
            }

        }
    }
    else {
    Write-Host "$i is not accessible"
    }
}

$Results | select -Property 'AD Group' -Unique | Export-Csv $outputfilelocation -NoTypeInformation

Its worth noting these errors do not stop my script from running its more of an aesthetic function as well as a learning opportunity for myself. I can use my script like it is but I would love to make it look cleaner and learn how to handle errors better.


Solution

  • Thank you @pwnosh you're a genius!

    I changed line 20 to

      if($errResults += try {$checkgroup = Get-ADGroup $perm -ErrorAction Stop } catch {[Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]}){
    

    This line forces the users into my CSV as well but then the second script cleans them out anyways with

    $results = @()
    foreach($Group in ($Groups = Import-csv C:\AD\Excel\permissions.csv)){
        $groupname = $Group.'AD Group'
        Write-Host "Confirming $groupname group name in AD."
        $results += get-adgroup -Filter "name -like '$groupname'" -Properties * -SearchBase "dc=domain,dc=local,dc=net" | select name
    }
    $results | Export-Csv C:\AD\Excel\ADGroups.csv -NoTypeInformation