Collect users with a certain attribute and clear the attribute.

Last week a college working with identity management needed a script to clear a dummy AD-attribute. All users that don´t have a telephone number needed a dummy phone number because of an external calendar system. This script collects all users with the telephoneNumber attribute 99999 in an variable and then exports the users in the variable with all their attributes before it clears the telephoneNumber attribute. We use it as an scheduled task.

Import-Module Activedirectory
# get date and time tog get the backup unique.
$date = get-date -Format yyyymmddHHmm
# Samla in användare som har 99999 som telefonnummer
# Collect users that hav 99999 as telephonenumber attribute.
$users = Get-ADUser -filter 'telephoneNumber -like "99999"' -Properties *

# Check if backup-file exists, if it exists stop the script and alert the usr, if it not exists export all users that is about to get the attribute changed.
if (Test-Path c:\temp\backup_$date.txt)
{Write-Host  "vänta en minut backupfilen finns redan" -BackgroundColor Yellow -ForegroundColor Red
    
}

else
{
Write-Host "exporterar användare" -BackgroundColor Black -ForegroundColor White
$users | Export-Csv c:\temp\backup_$date.txt -Encoding UTF8 -NoTypeInformation

foreach ($user in $users)
{
Write-Host "Clearing attribute on $user"
  Set-ADUser -Identity $user -Clear telephoneNumber
}
}