I'm hit and miss when it comes to writing PowerShell these days. I currently have a CSV with the following headers - Name, UserName, EXT, UserPrincipleName. I need to add the column data for OtherTelephone into each user's AD profile. I have a basic script going but I wanted to see if I was missing anything or if something needed to be corrected. I've added data to non-array attributes but wasnt sure if it was the same.
$users = Import-csv -path ".\extensions.csv"
foreach ($ext in $users {
Get-ADUser -Fi * -prop othertelephone -searchbase "MyOU" | select name,@{n="othertelephone";e={$_.othertelephone -join ";"}} | Set-aduser $_.userName -add @{othertelephone = $ext}
Thanks. And as always, I appreciate the help.
CodePudding user response:
Since LDAP attribute otherTelephone is a multivalued (string array) property, I would first check to see if perhaps the new extension from the csv is already set for that user. Then, if it is not, add it to the existing array.
Try
$searchBase = "OU=MyOU, ...."
$users = Import-csv -Path ".\extensions.csv"
foreach ($user in $users) {
# first check, is csv field EXT populated?
if ([string]::IsNullOrWhiteSpace($user.EXT) {
Write-Warning "Empty extension value for user $($user.Name) in the CSV.."
continue # skip this one and proceed with the next
}
# try and find the user using its UserPrincipalName
$adUser = Get-ADUser -Filter "UserPrincipalName -eq '$($user.UserPrincipalName)'" -Properties otherTelephone -Searchbase $searchBase
if ($adUser) {
# test if the new extension has already been set (otherTelephone is an array)
if ($adUser.otherTelephone -contains $user.EXT) {
Write-Host "Extension $($user.EXT) is already set for user $($user.Name).."
}
else {
Write-Host "Adding extension $($user.EXT) to user $($user.Name)"
# add the new extension to whatever is already set
# using -Add or -Replace usually wants strongly typed object arrays
# therefore the cast to [string[]]
[string[]]$extensions = @($user.EXT) $adUser.otherTelephone
$adUser | Set-ADUser -Replace @{otherTelephone = $extensions}
}
}
else {
Write-Host "User $($user.Name) not found.."
}
}
Please note the property is called UserPrincipalName
, not as stated in the question UserPrincipleName
.