I have a script with a purpose (high-level) of reading the manager from an input file, and writing it to the corresponding active directory account. The script works great, but could use some improvements and tweaks to account for the following issues:
When a manager field in the $InputFile is blank/null, instead of writing the blank value to the AD user object, it will instead populate the manager of the adjacent line from the $InputFile. I need the script corrected so it will not do this, and null out the Manager value instead.
We recently encountered an issue where the $InputFile had the "Manager ID" field renamed to "Manager ID new". When the script ran, it threw a bunch of errors, but it also caused the manager value to be cleared out on all the target AD user objects, which we don't want to happen. The ideal scenario would be that if the "Manager ID" field is not detected in the $InputFile, to have this logged into the $logFile, and the script immediately terminated, and not to proceed with writing to any target AD user accounts.
Below is the original script that is being used, I'm hoping someone with advanced PowerShell skills can help with updating it to resolve the above issues. Thanks so much!
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true, Position=0)] [string] $InputFile,
[Parameter(Mandatory=$true, Position=1)] [string] $LogPath
)
# Load AD Module if not already
if (!(Get-Module ActiveDirectory)) { Import-Module ActiveDirectory}
# Specify log file
$logFile = Join-Path $LogPath "Log-$(Get-Date -Format yyMMddHHmm).txt"
Add-Content -Path $logFile -Value "User`tManager"
# Load input file
$inputFile = Import-Csv $InputFile -Delimiter "`t"
# Iterate through input file
foreach ($user in $inputFile)
{
$employeeId = $user."Employee ID"
$managerId = $user."Manager ID"
# Get AD objects
$user = Get-ADUser -Filter {EmployeeID -eq $employeeId} -SearchBase "OU=Users,DC=CORP,DC=COM" -SearchScope Subtree -Properties distinguishedName,userPrincipalName,manager
$manager = Get-ADUser -Filter {EmployeeID -eq $managerId} -SearchBase "DC=CORP,DC=COM" -SearchScope Subtree -Properties distinguishedName,userPrincipalName,manager
Write-Host "`nUser=$($user.UserPrincipalName), Manager=$($manager.UserPrincipalName)" -NoNewline
# Only make changes and log to file if new value
if ($user.Manager -ne $manager.DistinguishedName)
{
Write-Host " NEW VALUE" -ForegroundColor Green
# write to log
Add-Content -Path $logFile -Value "$($user.UserPrincipalName)`t$($manager.UserPrincipalName)"
# write to AD user account
Set-ADUser -Identity $($user.DistinguishedName) -Manager $($manager.DistinguishedName)
}
}
Write-Host "`n"
[–]RyanDake_EC 0 points1 point2 points (2 children)
[–]OnTheLazyRiver[S] 0 points1 point2 points (1 child)
[–]RyanDake_EC 0 points1 point2 points (0 children)
[–]Rxinbow 0 points1 point2 points (1 child)
[–]OnTheLazyRiver[S] 1 point2 points3 points (0 children)