-1

First of all I am just learner with PS please bear with me.

I have managed to tweak a script (which I still need to test!) that will perform bulk updates of the manager field of AD user.

Using the username of the user and the username of the manager, where it will read CSV file which contains 2 fields: EmployeeUserName ManagerUserName:

Import-Csv "C:\Users\Temp\UpdateManagers.csv" |
    ForEach-Object {
        $ADUser  =  Get-ADUser -Filter "sAMAccountName -eq '$($User.EmployeeUserName)'"
        $manager = (Get-ADUser -Filter "sAMAccountName -eq '$($User.'ManagerUserName')'").distinguishedname

        if ($ADUser -and $manager) {
            $ADUser | Set-ADUser -manager $manager
        }
    }

My CSV format is:

CSV format

I wanted to know if someone could assist me with my script to output the results to an CSV file to state the username of a user that has had the manager updated in field and the new manager username in field.

UPDATE 1

@Theo sorry for the delay on this I ran your code (changed the file locations to work for me).

Didn't get any error but got this output below:

CSV output file

Then I checked the users and managers weren't updated:

AD User Manager Details

I don't know why it is not updating usernames are correct for both managers and users and I have ran PS ISE as Administrator...

UPDATE 2

Ran the updated code and got this error message:

PS C:\Windows\system32> C:\Users\Temp\BulkADManagerChange.ps1
Get-ADUser : Cannot find an object with identity: 'sAMAccountName -eq 'Manager1'' under: 'DC=my,DC=domain,DC=net'.
At CC:\Users\Temp\BulkADManagerChange.ps1:18 char:22
+         $ADManager = Get-ADUser "sAMAccountName -eq '$csvManager'"
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (sAMAccountName -eq 'Manager1':ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetAD 
   User
 
WARNING: Manager 'Manager1' does not exist
Get-ADUser : Cannot find an object with identity: 'sAMAccountName -eq 'Manager2'' under: 'DC=my,DC=domain,DC=net'.
At C:\Users\Temp\BulkADManagerChange.ps1:18 char:22
+         $ADManager = Get-ADUser "sAMAccountName -eq '$csvManager'"
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (sAMAccountName -eq 'Manager2':ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetAD 
   User
 
WARNING: Manager 'Manager2' does not exist
Get-ADUser : Cannot find an object with identity: 'sAMAccountName -eq 'Manager3'' under: 'DC=my,DC=domain,DC=net'.
At C:\Users\Temp\BulkADManagerChange.ps1:18 char:22
+         $ADManager = Get-ADUser "sAMAccountName -eq '$csvManager'"
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (sAMAccountName -eq 'Manager3':ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetAD 
   User
 
WARNING: Manager 'Manager3' does not exist
Get-ADUser : Cannot find an object with identity: 'sAMAccountName -eq 'Manager1'' under: 'DC=my,DC=domain,DC=net'.
At C:\Users\Temp\BulkADManagerChange.ps1:18 char:22
+         $ADManager = Get-ADUser "sAMAccountName -eq '$csvManager'"
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (sAMAccountName -eq 'Manager1':ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetAD 
   User
 
WARNING: Manager 'Manager1' does not exist

User           NewManager Result                                  
----           ---------- ------                                  
User1                     Error: Manager 'Manager1' does not exist
User2                     Error: Manager 'Manager2' does not exist
User3                     Error: Manager 'Manager3' does not exist
User4                     Error: Manager 'Manager1' does not exist

This was the CSV used by the code:

Latest CSV used

This was the results CSV file:

CSV results file

I can confirm in CSV file usernames of users and usernames of manager are correct.

Is it worth adding delimiters in the usernames using ';' ?

UPDATE 3

@Theo ran you code

It is sooo close!! It works updates AD fine BUT the code produces the errors below:

Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null or an element of the argument collection contains a null value.
At C:\Users\Me\Desktop\BulkADManagerChange.ps1:21 char:52
+             $currentManager = Get-ADUser -Identity $ADUser.Manager -ErrorAction  ...
+                                                    ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
 
Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null or an element of the argument collection contains a null value.
At C:\Users\Me\Desktop\BulkADManagerChange.ps1:21 char:52
+             $currentManager = Get-ADUser -Identity $ADUser.Manager -ErrorAction  ...
+                                                    ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
 
Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null or an element of the argument collection contains a null value.
At C:\Users\Me\Desktop\BulkADManagerChange.ps1:21 char:52
+             $currentManager = Get-ADUser -Identity $ADUser.Manager -ErrorAction  ...
+                                                    ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
 
Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null or an element of the argument collection contains a null value.
At C:\Users\Me\Desktop\BulkADManagerChange.ps1:21 char:52
+             $currentManager = Get-ADUser -Identity $ADUser.Manager -ErrorAction  ...
+                                                    ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
 

User           NewManager Result                                           
----           ---------- ------                                           
User1          Manager1   Success: New manager 'Manager1' set for this user
User2          Manager2   Success: New manager 'Manager2' set for this user
User3          Manager3   Success: New manager 'Manager3' set for this user
User4          Manager1   Success: New manager 'Manager1' set for this user

The output CSV file is fine also

Final CSV Output

S.Mahmood
  • 129
  • 11
  • 1
    Your code looks good and should do whats intended so the question is purely how to create an export with all the updates done right? – Santiago Squarzon Mar 28 '23 at 17:13
  • Yes, I was assuming my code may need some polishing touches (tweaks) by the PS experts on here. I would like assistance to create export the updates done in CSV file. – S.Mahmood Mar 29 '23 at 17:04
  • 1
    Don't post images of sample data. Use the built in table formatting. https://meta.stackoverflow.com/q/277716/3043 – Joel Coehoorn Mar 30 '23 at 16:02
  • @JoelCoehoorn I didn't know you could do that. I will do this now in the future thanks! – S.Mahmood Apr 05 '23 at 16:18

1 Answers1

1

If you want output for this where you want error/success messages, I would extend your code to something like below:

$result = Import-Csv "C:\Users\Temp\UpdateManagers.csv" | ForEach-Object {
    $csvUser    = $_.EmployeeUserName  # for convenience
    $csvManager = $_.ManagerUserName
    # create an object to output
    $out = [PsCustomObject]@{User = $csvUser; NewManager = $null; Result = $null }

    # if there is no manager found in the csv:
    if ([string]::IsNullOrWhiteSpace($csvManager)) {
        Write-Warning "User '$csvUser' does not have a manager specified in the csv"
        $out.Result = "Error: User does not have a manager specified in the csv"
        $out
        continue
    }

    $ADUser = Get-ADUser -Filter "sAMAccountName -eq '$csvUser'" -Properties Manager
    if ($ADUser) {
        # try and get the user object for the manager as stated in the csv
        $ADManager = Get-ADUser -Filter "sAMAccountName -eq '$csvManager'"
        if ($ADManager) {
            $out.NewManager = $csvManager
            try {
                $currentManager = (Get-ADUser -Identity $ADUser.Manager -ErrorAction Stop).SamAccountName
            }
            catch { $currentManager = $null }
            if ($currentManager -ne $csvManager) {
                $ADUser | Set-ADUser -Manager $ADManager.DistinguishedName
                $out.Result = "Success: New manager '$csvManager' set for this user"
            }
            else {
                $out.Result = "Skipped: Manager for this user was already correct"
            }
        }
        else {
            Write-Warning "Manager '$csvManager' does not exist"
            $out.Result = "Error: Manager '$csvManager' does not exist"
        }
    }
    else {
        Write-Warning "User '$csvUser' does not exist"
        $out.Result = "Error: User '$csvUser' does not exist"
    }
    # output the object so it gets collected in variable $result
    $out
}

# output result on screen
$result | Format-Table -AutoSize

# write result to csv file
$result | Export-Csv -Path 'X:\Somewhere\UpdateManagersResults.csv' -NoTypeInformation
Theo
  • 57,719
  • 8
  • 24
  • 41
  • could you see my last update (sorry for the delay had quite a lot on) – S.Mahmood Apr 12 '23 at 17:33
  • 1
    @S.Mahmood Ah, I think I made some mistakes before. Please try again. As long as your csv contains SamAccountNames for both the EmployeeUserName and the ManagerUserName field this should work. – Theo Apr 12 '23 at 18:44
  • could you take a look at update 2 on my questions - please could you assist? – S.Mahmood Apr 16 '23 at 16:21
  • 1
    @S.Mahmood Yep, I forgot the parameter name `-Filter` in line `$ADManager = Get-ADUser ...`, and by doing so, Powershell went for the first positional parameter which is `-Identity` for this cmdlet. Fixed now. – Theo Apr 16 '23 at 19:50
  • ran the code please see update 3 it is really close to working! – S.Mahmood Apr 17 '23 at 17:18
  • @S.Mahmood Aha, that means some users did not have a manager set. I have wrapped that part for the $currentManager now in a `try{..} catch{..}` – Theo Apr 18 '23 at 19:21
  • Yes, I forgot to state most users will be blank sorry.. Thanks it works perfect now. This will sound cheeky but I have asked another question regarding "Bulk AD Account creation with user expiry date set" no on is assisting could you have a look? – S.Mahmood Apr 19 '23 at 18:32