I am new to PS and AD, I am writing a script that loops through a csv and updates our AD. I am having several issues, where if the field is populated the PS AD Command runs fine, if the variable is null or empty then the PS Command Fails. I find it hard to believe AD can't handle null values, so I don't know if I am doing something wrong.
I have tried to do single commands for each to identify if it is the null causing the issue and I can see that is what is happening.
$datetime= get-date -UFormat "%Y-%m-%d_%H-%M-%S"
Import-Csv D:\adupdate.csv | ForEach-Object {
$hdate = $_."hiredate" -as [datetime]
Set-ADUser $_.UserID -DisplayName $_.DisplayName -Initials $_.Middle -Manager $_.Manager -Surname $_.LastName -givenname $_.FirstName -Office $_.Office -Department $_.Department -officeNumber $_.TeleNumber -MobilePhone $_.Mobile -Title $_.JobTitle -Company $_.Company -replace @{employeeType=$_.EmployeeType;employeeID=$_.Badge;employeeNumber=$_.EmployeeNumber;extensionAttribute3=$_.Subdepartment;ipPhone=$_.ipPhone}
Set-ADUser $_.UserID -replace @{hireDate=$hdate}
}
Error:
+ CategoryInfo : InvalidOperation: (XXX:ADUser) [Set-ADUser], ADInvalidOperationException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.SetADUser
So I changed into this, but seems inefficient checking for every variable from csv to check if null or empty:
if(-not ([string]::IsNullOrEmpty($_.employeetype))){Set-ADUser $_.userid -Replace @{'employeeType'=$_.employeetype}}
else {Set-ADUser $_.userid - -Replace @{'employeeType'=' '}}
if(-not ([string]::IsNullOrEmpty($_.badgenumber))) {Set-ADUser $_.userid -Replace @{'employeeID'=$_.badgenumber}}
else {Set-ADUser $_.userid -Replace @{'employeeID'= ' '}}
if(-not ([string]::IsNullOrEmpty($_.eecode))) {Set-ADUser $_.userid -Replace @{'employeeNumber'=$_.eecode}}
else {Set-ADUser $_.userid -Replace @{'employeeNumber'= ' '}}
if(-not ([string]::IsNullOrEmpty($_.subdepartment))) {Set-ADUser $_.userid -Replace @{'extensionAttribute3'=$_.subdepartment}}
else{Set-ADUser $_.userid -Replace @{'extensionAttribute3'=' '}}
if(-not ([string]::IsNullOrEmpty($_.ipphone))) {Set-ADUser $_.userid -Replace @{'ipPhone'=$_.ipphone}}
else{Set-ADUser $_.userid -Replace @{'ipPhone'=' '}}