Link to home
Start Free TrialLog in
Avatar of Larry David
Larry David

asked on

Update Empty Attributes - Powershell AD

Question, below was a script that I had assistance on a couple weeks back.

This script runs nightly to update extension attributes.

My concern was that if an employee ended up needing less attributes updated, this script won't update the empty attributes they won't need.

Any idea how to add that in here?

$inFile = 'C:\temp\empid.csv'
$outFile = 'C:\temp\empid_log.csv'
Import-Csv -Path $inFile | ForEach-Object {
	Write-Host "Processing $($_.EmployeeID)"
	$out = $_ | Select-Object -Property EmployeeID, SamAccountName, Result
	$hash = @{}
	If ($_.stuff)	{$hash['ExtensionAttribute1'] = $_.stuff}
	If ($_.things)	{$hash['ExtensionAttribute2'] = $_.things}
	If ($_.list)	{$hash['ExtensionAttribute3'] = $_.list}
	If ($_.nice)	{$hash['ExtensionAttribute4'] = $_.nice}
	#Set-ADUser $_.sAMAccountName -Replace $hash
	Try {
		If ($adUser = Get-ADUser -Filter "EmployeeID -eq $($_.EmployeeID)" -ErrorAction Stop) {
			If ($adUser.Count -gt 1) {
				$out.Result = "ERROR: Duplicate EmployeeID: $(($adUser | Select-Object -ExpandProperty SamAccountName) -join ', ')"
			} Else {
				$out.SamAccountName = $adUser.SamAccountName
				If ($hash.Count -gt 0) {
					$adUser | Set-ADUser -Replace $hash -ErrorAction Stop
					$out.Result = "Successfully set $($hash.Keys -join ', ')."
				} Else {
					$out.Result = "No attribute defined."
				}
			}
		} Else {
			$out.Result = "ERROR: EmployeeID not found!"
		}
	} Catch { 
		$out.Result = "ERROR: $($_.Exception.Message)"
	}
	$out
} | Export-Csv -NoTypeInformation -Path $outFile

Open in new window


Thank you
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Larry David
Larry David

ASKER

Yes! You do understand correctly! So after i attempted this script, i got the following error
ERROR: Cannot validate argument on parameter 'Identity'. The argument is null. Supply a non-null argument and try the command again.

Open in new window

in the excel output.

In Powershell ISE the error i see is:
Cannot index into a null array.
At line:24 char:32
+     If ($replace.Count -gt 0)    {$splat['Replace'] = $replace}

Open in new window

Actually, nevermind!!!! I saw that I missed
$splat = @{}

Open in new window


After adding that, everything works fine now!

Thank you