I wrote a script to move our service accounts first names to last names and keep it up to date as service accounts are created in Active Directory. It works and logs the changes, except the else part of the script. For some reason, it will not execute the else statement when the if isn't true. Please keep in mind that I am still a beginner to PowerShell...
$runStartTime = Get-Date -Format g
$workingDir = "c:\bin\"
$logfile = $workingDir +" LastNameChg.txt"
Add-Content $logfile "-----| LogFile: $logfile"
Add-Content $logfile "-----| Users last names changed in Active Directory on $runStartTime :"
Import-Module ActiveDirectory
$users = Get-ADUser -searchbase "OU=Testing,OU=Service Accounts,DC=test,DC=907,DC=local" -LDAPFilter {(&(objectCategory=user)(objectClass=user)(mail=*)(!(sn=*)))}
foreach ($user in $users){
$logdata = $user.sAMAccountName
if ($user.GivenName -ne $null){
Get-ADUser $user | Set-ADUser -surname $($user.givenName) -givenname $()
Add-Content $logfile "-----| $logdata"
}
else{
Add-Content $logfile "-----| No changes made to Active Directory"
}
}
Add-Content $logfile ""
if ($user.GivenName -ne ""){- maybe the GivenName is either some text or an empty string, and is never $null. Just guessing.$user.GivenNameis most likely""(an empty string) and not$null. Remove-ne $nullfrom the if statement and it'll workif(-not [string]::IsNullOrWhitespace($user.GivenName))which catches null, whitespace, or empty