Friday, September 27, 2019

Upate Active Directory User's Manager with Powershell

Problem,

Need to replace manager for multiple users in Active Directory (AD)

Solution
First we need to find what users have a giving manager.

This script will query AD for users with given manager SAM account name.

#
#   Get AD User's Manager
#
#

Param(
    [Parameter(Mandatory=$false,
        ValueFromPipeline=$true)]
        $FindManagerSamAccountName

    ,[Parameter(Mandatory=$false,
        ValueFromPipeline=$true)]
        $FindUserSamAccountName 
)

#Check if AD is installed
$ADUsersManagers = ""
    If (!(Get-Module ActiveDirectory)) {
        Import-Module ActiveDirectory
    }

$ADUserList =""
if ([string]::IsNullOrEmpty($FindUserSamAccountName)) {
    $ADUserList = Get-ADUser -Filter { Enabled -eq $true } -Properties Manager 
    } else {
    $ADUserList = Get-ADUser -Filter {SamAccountName -eq $FindUserSamAccountName } -Properties Manager                 
    }

$ADUsersManagers = $ADUserList|Select-Object Name,SamAccountName,@{n='ManagerSamAccountName';e={(Get-aduser $_.Manager).SamAccountName}} 

   if (![string]::IsNullOrEmpty($FindManagerSamAccountName)) {
        $ADUsersManagers |Where-Object {($_.ManagerSamAccountName -eq $FindManagerSamAccountName)}
        } else {
            $ADUsersManagers}

No comments:

Post a Comment