Powershell – set-aduser inside foreach loop

powershell

I'm trying to get the below script to change three things on an AD account. I want it to expire the account, change an attribute, and append disabled account to the current description. It does everything except append the description. As it stands the script just replaces the description field with Disabled Account instead of append it to what is already there.

$Yesterday = (Get-Date).AddDays(-1)
$DisableUserList = Get-Content C:\Myscripts\test.csv
$DisableUsers = foreach ($user in $DisableUserList) { get-aduser -filter { mail -eq $user } }


ForEach ($user in $DisableUsers) {
        Set-ADUser $user -Description "Disabled Account $($_.Description)" -AccountExpirationDate $Yesterday -replace @{ businesscategory = "21" }
}

The .csv file only has one column of email addresses.

Any help is appreciated.

Thank you

Best Answer

Your problem is that the $($_.Description) part of your Set-ADUser command is empty. The reason is that Get-ADUser doesn't retrieve the account's description by default. You need to explicitly ask for it in your command like this:

get-aduser -filter { mail -eq $user } -Properties Description

Your other problem is that you're not referencing your disabled user properly within your final loop. You're currently using ForEach ($user in $DisabledUsers) which means to access properties on each user they need to be prefixed with $user.MyProperty instead of $_.MyProperty. If you want to use the $_ notation, you need to change the style of your for loop to this:

$DisabledUsers | ForEach-Object { 

You can also shorten that to just:

$DisabledUsers | % {

Finally, you say you want to append (add to the end) your text to the current description, but your code is currently trying to prepend (add to the beginning). Assuming you do actually want to append, you'd need to change your description string definition to this:

-Description "$($_.Description) Disabled Account"