Solved

AD User Modification PS script won't update user properties if manager ID is not available in AD

Posted on 2016-10-22
8
76 Views
Last Modified: 2016-10-24
Help required for user modification script on list of users

The script has condition that if user manager is available in AD, set the same along with other properties, if not it should update the other properties

# Start of script
Import-Module ActiveDirectory

# Import File
$Users = Import-Csv "C:\userupdate\users.csv"
#Processing each user
Foreach ($User in $Users) {
    
    try {
        $ADUser = $null

        
        $ADUser = Get-ADUser -Identity $User.Username -ErrorAction SilentlyContinue
        if ($ADUser -ne $null) {
            $Manager = $null
            $Manager = Get-ADUser -Identity $User.ManagerID -ErrorAction SilentlyContinue
            if ($Manager -ne $null) {
                Set-ADUser -Identity $ADUser -Department $User.Department -Manager $user.ManagerID `
                -EmailAddress $User.Email -Company $user.Company -MobilePhone $user.CellPhone -Title $user.Title
                                
            }
            else {
                Set-ADUser -Identity $ADUser -Department $User.Department `
                -EmailAddress $User.Email -Company $user.Company -MobilePhone $user.CellPhone -Title $user.Title
                
            }
        }
       
             "$($ADUser.sAMAccountName), User Modified Successfully" | Out-File -FilePath "C:\userupdate\result.txt" -Append -Force
    }
# Catch error if any
    catch {
        "$($ADUser.sAMAccountName), Failed" | Out-File -FilePath "C:\userupdate\result.txt" -Append -Force
        $error[0] | Out-File "C:\userupdate\errorlog.txt" -Append
    }
}

Open in new window


No matter what I do, if manager ID is not available in AD, script simply won't process that user and don,t update other properties of that user

I wanted that if manager id is not available in AD, still script should process other properties

Any help would be highly appreciated
0
Comment
Question by:Mahesh
8 Comments
 
LVL 39

Expert Comment

by:footech
ID: 41856186
Try modifying line 23 to
$ADUser | Set-ADUser -Department $User.Department `

Open in new window


Also, why are you setting -ErrorAction to SilentlyContinue?  It pretty much negates the purpose of the try...catch block.
0
 
LVL 79

Expert Comment

by:David Johnson, CD, MVP
ID: 41856284
Does every user in your csv have a ManagerID?
Line 18
if (($Manager -ne $null) -and ($user.ManagerID -ne $nulll) ){
0
 
LVL 35

Author Comment

by:Mahesh
ID: 41856295
Tried that

Still no luck

what should be -Erroraction ?
0
 
LVL 35

Author Comment

by:Mahesh
ID: 41856297
yes csv has managerID defined because it is import from some other HRMS tool but those managerID may not available in AD

As soon as script did not find managerID in AD, it simply ignore that user by ignoring all conditions (if else etc)
0
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 
LVL 24

Accepted Solution

by:
Coralon earned 250 total points
ID: 41856381
You might try reworking it.. something like this..
Import-Module -Name ActiveDirectory -ErrorAction SilentlyContinue

$Users = Import-Csv -Path 'C:\userupdate\users.csv'

foreach ($User in $Users)
{
	Try
	{
		$ADUser = Get-ADUser -identity $User.UserName 
		Try
		{
		Set-ADUser -Identity $ADUser -Department $User.Department -EmailAddress $User.Email -Company $user.Company -MobilePhone $user.CellPhone -Title $user.Title
		}
		catch
		{
			"$($ADUser.sAMAccountName), User Modified Successfully (base properties)" | Out-File -FilePath "C:\userupdate\result.txt" -Append -Force
		}
		$ManagerID = $User.ManagerID
		
		if ($ManagerID) 
		{
			Try
			{
				$Manager = Get-ADUser -identity $ManagerID 
				Set-ADUser -identity $ADUser -Manager $Manager 
				"$($ADUser.sAMAccountName), User Modified Successfully" | Out-File -FilePath "C:\userupdate\result.txt" -Append -Force
			}
			catch
			{
				Write-Output "The ManagerID for $($User.username) does not exist in ActiveDirectory"
			}
		}
		else
		{
			Write-Output "No ManagerID specified for $($User.UserName)"
		}
	}
	catch
	{
		"$($ADUser.sAMAccountName), Failed" | Out-File -FilePath 'C:\userupdate\result.txt' -Append -Force
        $error[0] | Out-File 'C:\userupdate\errorlog.txt' -Append
	{
	Remove-Variable ManagerID, Manager
}

Open in new window


Coralon
0
 
LVL 39

Assisted Solution

by:footech
footech earned 250 total points
ID: 41857481
I take back my comment about the -ErrorAction parameter.  I thought that Get-ADUser threw a non-terminating error, and you had to set -ErrorAction to Stop (making the error terminating) to get Try/Catch to work with it.  But I can't replicate the behavior now, so maybe my memory is faulty.  In any case, what was happening with your original code was that as soon as any error was thrown by the Get-ADUser command, whether on line 13 or 16, the catch block would be called to handle it.

I think Coralon's approach is good using multiple try/catch blocks.  Another way would be to change your Get-ADUser commands to use the -Filter parameter instead of -Identity, which won't through any errors if no matches are found.
0
 
LVL 35

Author Comment

by:Mahesh
ID: 41858038
"Get-Aduser" if identity failed / didn't exists, it will pass on to next line in csv file

Basically if I try to modify "Manager" field along with other attributes, if manager id is not available in AD, it will simply ignore user for attributes as well.

I tried "if else" loop with filter specified for manager id and it also working, but then its unable to generate error code in errorlogfile if manager id is not available in AD

Hence I moved manager id modification to new line and now its started working.
I have modified code as below

# Start of script
Import-Module ActiveDirectory -ErrorAction Stop

# Define result and error log file
$DateTime = Get-Date -Format ddMMyyyy_HHmm
$ResultLogFile = "C:\userupdate\ResultLogFile_$DateTime.txt"
$ErrorLogFile = "C:\userupdate\ErrorLogFile_$DateTime.txt"
# Import File
$Users = Import-Csv "C:\userupdate\users.csv"
#Processing each user
Foreach ($User in $Users) {
    
    try {
        $ADUser = $null

        $ADUser = Get-ADUser -Identity $User.Username -ErrorAction SilentlyContinue
        if ($ADUser -ne $null) {
                Set-ADUser -Identity $ADUser -Department $User.Department -Manager $user.ManagerID `
                -EmailAddress $User.Email -Company $user.Company -MobilePhone $user.CellPhone -Title $user.Title
		        Set-Aduser -Identity $ADUser -Manager $user.ManagerID -ErrorAction SilentlyContinue }
            											       
	"$($ADUser.sAMAccountName), User Modified Successfully" | Out-File -FilePath $ResultLogFile -Append -Force
        }
            
       
# Catch error if any
    catch {
            if($ADUser.SamAccountName -eq $null) 
                { 
                    "$($user.Username),Account does not exists in AD" | Out-File -FilePath $ResultLogFile -Append -Force 
                                                                                                                          }
            else
                    { 
                      "$($ADUser.SamAccountName),User Modified Successfully but failed to update Manager field because its not availabe in AD" | Out-File -FilePath $ResultLogFile -Append -Force 
                                                                                                                                                                                                    }
                $($ADuser.SamAccountName) + " : " + $error[0].ToString() | Out-File $ErrorLogFile -Append
    }
}

Open in new window

0
 
LVL 35

Author Closing Comment

by:Mahesh
ID: 41858039
I am awarding points to Coralon and Footech both because both have provided valid inputs which helps me to resolve the issue
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When you start your Windows 10 PC and got an "Operating system not found" error or just saw  "Auto repair for startup" or a blinking cursor with black screen. A loop for Auto repair will start but fix nothing.  You will be panic as there are no back…
In this article, I will show you HOW TO: Install VMware Tools for Windows on a VMware Windows virtual machine on a VMware vSphere Hypervisor 6.5 (ESXi 6.5) Host Server, using the VMware Host Client. The virtual machine has Windows Server 2016 instal…
This tutorial will walk an individual through the steps necessary to join and promote the first Windows Server 2012 domain controller into an Active Directory environment running on Windows Server 2008. Determine the location of the FSMO roles by lo…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…

861 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now