Get-aduser Filter QUESTION

This topic contains 10 replies, has 4 voices, and was last updated by Profile photo of James James 9 months, 2 weeks ago.

  • Author
    Posts
  • #35622
    Profile photo of James
    James
    Participant

    I have a script that I wrote to scan for home directories not matching active directory, I am having a problem when I Try to make Get-Aduser Filter {samaccount name -eq $share} I even tried to give that a new variable and still couldn't get it to catch the ones no in AD. Here is my script if anyone can help I would appreciate it I want it so I can apply a searchbase paramater.

  • #35627
    Profile photo of Richard Siddaway
    Richard Siddaway
    Moderator

    This worked on my Windows 2012 R2 environment

    $path = 'C:\Folders'

    $shares = Get-ChildItem -Path $path -Directory | select -ExpandProperty Name
    foreach ($share in $shares) {
    Get-ADUser -Identity $share
    }

  • #35630
    Profile photo of James
    James
    Participant

    Thanks for the comment, but what about for -Filter as I want to be able to apply a searchbase.
    Thanks for the comment it is crazy to have someone comment that you read a book from. Great work and I really appreciate the comment.

  • #35633
    Profile photo of Joshua Barton
    Joshua Barton
    Participant

    Hey James,

    Could you copy in the exact code that is malfunctioning? The version with your filter? That will be easier for someone to look at than different code with a comment above it.

  • #35635
    Profile photo of James
    James
    Participant

    Thanks Joshua,
    I guess this is what I want
    I want it to catch all the ones that are missing in Active Directory

    $path = '//share/path/'
    
    $shares = Get-ChildItem -Path $path -Directory | select -ExpandProperty Name
    foreach ($Share in $Shares){
                try{
                #also Tried Get-Aduser -Filter {Samaccountname -eq $share}
               $user =  Get-ADUser -Filter {Samaccountname -eq $share}
               $user
                }
                catch{
    
               $user | Out-File C:\test1.txt -Append 
                }
                }
    
  • #35639
    Profile photo of Richard Siddaway
    Richard Siddaway
    Moderator

    $path = 'C:\Folders'

    $shares = Get-ChildItem -Path $path -Directory | select -ExpandProperty Name
    foreach ($share in $shares) {
    Get-ADUser -Filter {SamAccountName -eq $share}
    }

    works for me

    Your code won't work if the account doesn't exist – $user will be NULL.

    You actually have a very subtle problem
    Compare these outputs

    PS> Get-ADUser -Identity dontexist
    Get-ADUser : Cannot find an object with identity: 'dontexist' under: 'DC=Manticore,DC=org'.
    At line:1 char:1
    + Get-ADUser -Identity dontexist
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : ObjectNotFound: (dontexist:ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser

    PS> Get-ADUser -Filter {SamAccountName -eq 'dontexist'}

    If you use a filter you're allowed to have result where nothing matches the filter

    If you want to catch where a user can't be found then use
    $path = 'C:\Folders'

    $shares = Get-ChildItem -Path $path -Directory | select -ExpandProperty Name
    foreach ($share in $shares) {
    $user = Get-ADUser -Filter {SamAccountName -eq $share}
    $user
    if (-not $user) {
    Write-Warning "User $share NOT found"
    }
    }

    OR if you want the try-catch syntax

    $path = 'C:\Folders'

    $shares = Get-ChildItem -Path $path -Directory | select -ExpandProperty Name
    foreach ($share in $shares) {
    $user = $null
    try {
    $user = Get-ADUser -identity $share -ErrorAction Stop
    $user
    }
    catch {
    Write-Warning "User $share NOT found"
    }
    }

  • #35654
    Profile photo of James
    James
    Participant

    With your first option how could I create a custom object. So I can later work with like I did exporting the CSV. Basically I am trying to catch all folders not having a account in Ad. Thanks again for the help.

  • #35714
    Profile photo of Aapeli Hietikko
    Aapeli Hietikko
    Participant

    I think your script is sweet!

    Get-ADUser is cranky with the input variables. Try to define $samid = $share inside the ForEach loop. That will most likely fix your problem.

    I started to write my own version of this with few modifications, but the script is not ready yet. I'm still wondering if it really needs to be function or not. I did also take a slightly different approach with the get-aduser part. Instead of trying to match share name to sAMAccountName, I will try to find if some user has that share as homedirectory.

    Here is the raw start that I started to write 15 minutes ago

    $outputObjects = @()
    $folders = Get-ChildItem \\server\share | select -First 50
    
    foreach ($folder in $folders) {
        $samid = $folder.name
        $share = ($folder.FullName).replace('\','\5c')
    
        if (-not (get-aduser -fi {homedirectory -eq $share})) {
                $colItems = Get-ChildItem  -Path $folder.FullName -Recurse | Measure-Object -property length -sum -EA SilentlyContinue
                $ColItemsinMBytes =  "{0:N2}" -f ($colItems.sum / 1MB) + " MB"
                
         
                $properties = @{
                                "User" = $samid;
                                "HomePath" = $folder.FullName ;
                                "FolderSize" = $ColItemsinMBytes} 
    
                $obj = New-Object -TypeName PSCustomObject -Property $properties  
                $outputObjects += $obj
                } # End if (-not (get-aduser -fi {samaccountname -eq $samid}))
    
         } # End foreach ($folder in $folders)
    $outputObjects | Sort-Object foldersize -Descending | ft -AutoSize
    
  • #35740
    Profile photo of James
    James
    Participant

    @Aapeli Hietikko Thanks for the comments I will take a look and try your suggestions. The reason that I created a Function was because we have multiple shares based on department IT, Business, ...etc so I just copied and changed the path, which I thought would be easier with it wrapped in a Function. I plan to just call the function at the end of the script.

  • #35758
    Profile photo of Aapeli Hietikko
    Aapeli Hietikko
    Participant

    Glad to hear if it helped. My intentions were a bit different. We have lot of orphan home folders from users that have left the company. It would be quite ok to compare who is not found from AD anymore and delete, but I think that would be like shooting to own leg.

    Sometimes boss or colleague is granted permissions to clean up the folder and move any business critical files to somewhere else. So my goal is was to find all the orphan folders and list also custom NTFS permissions to see which of the folders might need more attention.

    In our environment all home directories are under one DFS share so it's quite easy to find them.

    $outputObjects = @()
    $defaultACLUsers = @('Administrators','HOMESHARE-ADMIN','System','Users','FILESHARE-ADMINS')
    $shareFolders = Get-ChildItem \\domain\dfs\share | where {$_.name -like "Homedir*"}
    
    foreach ($folder in $shareFolders) {
        $folders = Get-ChildItem \\domain\dfs\share\$folder
        
        foreach ($folder in $folders) {
            $samid = $folder.name
            $share = ($folder.FullName).replace('\','\5c')
        
            if (-not (get-aduser -fi {homedirectory -eq $share})) {
                    $colItems = Get-ChildItem  -Path $folder.FullName -Recurse | Measure-Object -property length -sum -EA SilentlyContinue
                    [string]$ColItemsinMBytes =  "{0:N2}" -f ($colItems.sum / 1MB) + " MB"
                    
                    $permissions = ""
                    #End (Get-Acl $folder.fullName).access
                    $accounts = (Get-Acl $folder.FullName).access.IdentityReference | Sort-Object -Unique
                    foreach ($account in $accounts.Value) { 
                            
    	                    $acc = $account.split('\')[1]
                            
    	                    if (-not ($defaultACLUsers -match $acc)) {
    	                    	$permissions += "$acc;"
    	                    	} #End if (-not ($defaultACLUsers -match $account))
    
    	                    } #End (Get-Acl $folder).access | foreach
             
                    $properties = @{
                                    # "User/Folder" = $samid;
                                    "HomePath" = $folder.FullName
                                    "FolderSize" = $ColItemsinMBytes
                                    "Permissions" = $permissions -replace “.$”
                                    } 
        
                    $obj = New-Object -TypeName PSCustomObject -Property $properties  
                    $outputObjects += $obj
    
                    #$obj uncomment this if you want to see what happens
    
                    } #End if (-not (get-aduser -fi {samaccountname -eq $samid}))
             
             } #End foreach ($folder in $folders)
    
    } #End foreach ($folder in $shareFolders)
    
    $outputObjects | select HomePath, FolderSize, Permissions| Sort-Object foldersize -Descending | export-csv homedir.csv -NoTypeInformation -Encoding UTF8
    
  • #35772
    Profile photo of James
    James
    Participant

    This is awesome man, I agree and I like how you threw in the ACLs great addition. Thanks for sharing and providing assistance. I am still learning PoSh probably have really been at if for 6 months or so, but I can't get enough of automating and improving processes.

You must be logged in to reply to this topic.