0

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.

  • 2
    You're using "Get-ADGroup" for getting AD Users within your If-condition. If you want to throw errors for Users and catch those errors, I would suggest to add the `-ErrorAction ` parameter to Get-ADGroup, write the result of it into a new variable and enclose that with try-catch. E.g. `try { $adGroup = Get-ADGroup $perm -ErrorAction Stop} catch { ; continue}`. The continue-statement in the catch block will jump to the next $acl collection entry within your foreach loop. – swbbl Jan 15 '21 at 15:37
  • That worked but the code is too long to post in a comment i guess so ill post the answer to the question lower in case anyone else is looking for the same answer. – sam.solo.works Jan 15 '21 at 15:58

2 Answers2

1

As you indicate you are interested in learning more about error handling, one thing I learned this week are these common Parameters for error handling and recording:

-ErrorAction
-WarningAction
-ErrorVariable
-WarningVariable

You can silence the error messages by using the parameter -ErrorAction SilentlyContinue but capture the error by using the parameter -ErrorVariable

EXAMPLE: get-adgroup -ErrorAction SilentlyContinue -ErrorVariable MyErrors

You can read and manipulate the errors by calling $MyErrors

The warnings work the same way

It might give an alternative to Try/Catch.

sailingbikeruk
  • 164
  • 1
  • 8
  • When trying this answer instead I get a separate error of 'Get-ADGroup : Cannot convert 'System.Collections.ArrayList' to the type 'System.String' required by parameter 'ErrorVariable'. Specified method is not supported.' – sam.solo.works Jan 15 '21 at 16:44
  • Sorry I missed the $perm from the command I think, is this work any better? `Get-ADGroup $perm -ErrorAction SilentlyContinue -ErrorVariable $MyErrors ` – sailingbikeruk Jan 17 '21 at 11:55
0

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