none
PowerShell script : Directory object not found error in Get-ADGroupMember RRS feed

  • Question

  • I am new in powershell scripting. I am writing a script to add users in different AD Groups. while doing so I do the following:

    1. Check if the user already exist in the group:

      $mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAccountName -eq $sam}

    2. If user does not exist then add the user to the group.

    When I manually run the script its runs flawless, without any errors. But when I schedule the script to run it gives an error as follows:

    3/30/2015 8:32:15 AM Directory object not foundAt + $mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAc ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~ Error at Line:$mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAccountName -eq $sam}

    The strange thing is the user for which it throws the error is present in the group.I am not sure why this error is occurring when scheduled. Can any one please help? All the suggestions will be appreciated

    Note: (The script is scheduled using Windows Task Scheduler)

        try
        {
            # # Initialize the variables we will use
            $status        = 'false' 
    	$drivename     = "H:"
    	$sysdate       = Get-Date -UFormat "%m_%d_%Y"
    	$foldername    = $drivename + "\Script_Result\PowershellData"+ $sysdate
    	$backup_folder = "$foldername\AD_Groups_Backup"
            $updatedGroup  = "$foldername\Updated_AD_Groups_LogFiles"
    	$LogFilePath   = "$foldername\Log_Update_ADGroups"+$sysdate+".log"
    
            # # Initialize the arrays we will use
            $GroupArray = @()
            
            # # maintain log of program startup
            $logdate = get-date
            $logdate.ToString() + "`tStarted script to Update AD user Groups..." | Out-File -FilePath $LogFilePath
    
            # # Create a sub folder to store the backup files
            $fileexist = Test-Path $backup_folder -PathType Container
            if($fileexist -ne 'False')
            {
                New-Item -ItemType Directory $backup_folder
            }
            
            # # Create a sub folder to store Updated AD group Log files
            $fileexist = Test-Path $updatedGroup -PathType Container
            if($fileexist -ne 'False')
            {
                New-Item -ItemType Directory $updatedGroup
            }
            # # Take back up of the AD groups data
        
            Get-ADGroupMember -Identity "Group1" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
            Get-ADGroupMember -Identity "Group2" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
            Get-ADGroupMember -Identity "Group3" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
            Get-ADGroupMember -Identity "Group4" | Export-csv "$backup_folder\Group1_BackUP$sysdate.csv"
            (an so on..... 11 such groups )
    
            # # Fetch AD Users data 
            $ADusers = Get-ADUser -filter {(EmployeeNumber -gt 1) -and (EmployeeNumber -ne "N/A") -and (Enabled -eq $true)} -Properties * | Sort-Object -Property EmployeeNumber
            $ADusers.Count
            foreach($u in $ADusers)
            {
                $sam    = $u.SamAccountName
                $empnum = $u.EmployeeNumber
                $mgr    = $u.mgr
                $fsal   = $u.'fsalary-Hourly'
                $comp   = $u.Company
                $ofc    = $u.Office
                Write-Host "$sam : $empnum : $mgr :$fsal : $comp : $ofc" -ForegroundColor Yellow 
                $GroupArray = @()
                
                # # Check if the  user fits in any of the 11 scenarios 
                if($comp -eq "US")
                {
                   
                    # scenario 7 
                    write-host "7. Add to US Employees"
                    $GroupArray += "US Employees"
    
                    if($mgr -eq "Y")
                    {
                        Write-Host "1. ADD to US MAnagers"
                        $group = "US Managers"
                        $GroupArray += $group
                        
                    }
                    if(($fsal -eq "Hourly") -and ($ofc -ne "Canton"))
                    {
                        Write-Host "3. Add to US Hourly (excluding Canton)"
                        $group = "US Hourly (excluding Canton)"
                        $GroupArray += $group
                        
                    }
                    if(($fsal -eq "Hourly") -and ($ofc -eq "Canton"))
                    {
                        write-host "4. Add to US Canton Hourly"
                        $group = "US Canton Hourly"
                        $GroupArray += $group
                        
                    }
                    if(($fsal -eq "Salaried") -and ($ofc -eq "Corporate" -or $ofc -eq "Landis Lakes 1" -or $ofc -eq "Landis Lakes 2"))
                    {
                        Write-Host "5. Add to US Salaried Corporate"
                        $group = "US Salaried Corporate"
                        $GroupArray += $group
                        
                    }
                    
                    if(($fsal -eq "Salaried") -and ($ofc -ne "Corporate" -and $ofc -ne "Landis Lakes 1" -and $ofc -ne "Landis Lakes 2"))
                    {
                        Write-Host "6. Add to US Salaried Plant"
                        $group = "US Salaried Plant"
                        $GroupArray +=$group
                        
                    }
                    
             
           
                }
                elseif($comp -eq "canada")
                {
                    # scenario 9
                    write-host "9. Canada Employees"
                    $GroupArray += "Canada Employees"
                    
    
                    if($mgr -eq "Y")
                    {
                        Write-Host "2. Add to Canada Managers"
                        $group = "Canada Managers"
                        $GroupArray += $group
                        
                    }
                    if($fsal -eq "Hourly")
                    {
                        Write-Host "10. Add to Canada Hourly"
                        $group = "Canada Hourly"
                        $GroupArray += $group
                        
                    }
                    if($fsal -eq "Salaried")
                    {
                        Write-Host "11. Add to Canada Salaried Plant"
                        $group = "Canada Salaried Plant"
                        $GroupArray += $group
                         
                    }
                }
    
                elseif($ofc -eq "Corporate" -or $ofc -eq "Landis Lakes 1" -or $ofc -eq "Landis Lakes 2")
                {
                    Write-Host "8. Add to Corporate Employees"
                    $GroupArray += "Corporate Employees"
                }
                write-host "Final Group List" -ForegroundColor Green
                $grplen = $GroupArray.Length
                #$GroupArray
                $grplen
                 
                for($i= 0; $i -lt $grplen; $i++)
                {
                    $grpname = $GroupArray[$i]
                    write-host "$sam will be added to Group : $grpname" -ForegroundColor Magenta 
    
                    # # Check if the user is already present in the Group
                    $mbr_exist = Get-ADGroupMember $grpname | Where-Object {$_.SamAccountName -eq $sam}
                    if($mbr_exist -eq $null)
                    {
                        # #Add user to US Managers group
                        Add-ADGroupMember -Identity $grpname -Members $sam
    
                        Write-Host "1. User $sam is added to $grpname group" -ForegroundColor Green
    
                         # # documenting the user list that are added to this group
                        $grpmbr = New-Object PSObject
    	            $grpmbr | Add-Member -MemberType NoteProperty -Name "EmployeeNumber"    -Value $empnum
                        $grpmbr | Add-Member -MemberType NoteProperty -Name "SamAccountName"    -Value $sam
                        $grpmbr | Add-Member -MemberType NoteProperty -Name "Name"              -Value $u.Name
    	            $grpmbr | Add-Member -MemberType NoteProperty -Name "DistinguishedName" -Value $u.DistinguishedName
    	            $grpmbr | Add-Member -MemberType NoteProperty -Name "mgr"               -Value $mgr
                        $grpmbr | Add-Member -MemberType NoteProperty -Name "Company"           -Value $comp
                        $grpmbr | Add-Member -MemberType NoteProperty -Name "Salary/Hourly"     -Value $fsal
                        $grpmbr | Add-Member -MemberType NoteProperty -Name "Office"            -Value $ofc
                        $grpmbr | Add-Member -MemberType NoteProperty -Name "ADGroup"            -Value $grpname
    
                        $grpmbr | Export-Csv "$updatedGroup\ADUsers_To_Group($grpname)_$sysdate.csv" -Append -NoTypeInformation
                                
                    }
                    else
                    {
                       Write-Host "Member $sam already exist in $grpname group" -ForegroundColor Red
                    }
                }
        
        
            }
            $logdate     = get-date
            $logdate.ToString() + "`tCompleted script to Update Update AD Groups..." | Out-File -FilePath $LogFilePath -Append
            $status = 'true'
            return $status
        }
        
        catch
        {
             $err_lineno = $error[0].InvocationInfo.ScriptLineNumber
             $err_line = $error[0].InvocationInfo.Line
             $ExceptionMessage = $_.Exception.Message
             #$ExceptionMessage
             $error_info = $error[0].ToString() + $error[0].InvocationInfo.PositionMessage
             Write-Host "$error_info " -ForegroundColor Red
             $FailedItem = $_.Exception.ItemName
             if($ExceptionMessage)
              {
                   $logdate.ToString() + "`t $error_info " | out-file "$foldername\ErrorLog_Update_AD_Groups$sysdate.log" -append
                  "Line Number: $err_lineno . `nError at Line: $err_line" | out-file "$foldername\ErrorLog_Update_AD_Groups$sysdate.log" -append
                  #Invoke-Item "C:\ErrorLog.log"
                  $status = 'false'
              }
             
             return $status
        }


    • Edited by Pranav.L.J Wednesday, April 1, 2015 7:16 AM
    • Moved by Bill_Stewart Thursday, May 28, 2015 8:13 PM Off-topic/unanswerable
    Tuesday, March 31, 2015 6:21 AM

All replies

  • There is no way to help without knowing the whole script and the way it is scheduled.  You have not provided enough information.

    You can try hardcoding in the values for just that one line to prove that it is not AD or the script but a mistake in how you are scheduling it.


    ¯\_(ツ)_/¯

    Tuesday, March 31, 2015 6:28 AM
  • Hi jrv, Thank you for the suggestion. I have updated the post. 
    Tuesday, March 31, 2015 7:28 AM
  • How are you scheduling the job? If you are using task scheduler, did you set the script to run with your credentials, or under the system account? If this runs fine with your creds, you will want to make sure the sched task is also running with your creds.

    Tuesday, March 31, 2015 1:57 PM
  • Hi mdkelly, Sorry for such a late reply (due to credential issues).

    I am using Windows task scheduler to schedule the task. I am given the administrator access to the server (Windows Server 2012). So I think I set to run the script under system account.

    My apologies for asking this, am I missing something while scheduling the script through task scheduler?  how to check if the scheduled task is running under who's credentials? How to pass my (admin) credentials, so that the script execution won't face a problem? Any suggestion on the above questions will be helpful. (I tried to search on net for the questions but didn't get any conclusive answers)  

    Thanks in advance.


    • Edited by Pranav.L.J Tuesday, April 21, 2015 10:54 AM
    Tuesday, April 21, 2015 10:52 AM
  • Hello Pranav,

    You can use the below method to specify your account,

    Tuesday, April 21, 2015 1:46 PM
  • Thank you for the suggestion Vasu Deva. I will try it and post the results (success or failed) of scheduling on this post.
    • Edited by Pranav.L.J Wednesday, April 22, 2015 7:06 AM
    Wednesday, April 22, 2015 7:05 AM