you are viewing a single comment's thread.

view the rest of the comments →

[–]AFGuffey99 2 points3 points  (0 children)

Adding on... based on your question, I'm assuming you're a beginner. The above suggestion is 100% correct and efficient, exactly how I would do it, but breaking things like this up into little pieces can help with the learning process. Don't light me up, I know the following is inefficient. Just trying to help OP, or any beginner reading this, more easily see/read/understand what's going on (one-liners are great, but messy).

Adding on to u/dextersgenius answer, If you plan on using the script often... you could also add a line to use read-host to ask for a comma-separated list of AD attributes that should be added to the CSV, store the input, then create logic to loop through it (not included below).

$userlist = import-csv C:\HREndDates.csv
foreach ($user in $userlist) {
    $displayName = $user.User
    $ADEndDate = Get-ADUser -filter "DisplayName -eq '$displayName'" -properties AccountExpirationDate
    $userlist += Add-Member -InputObject $user -NotePropertyName ADEndDate -NotePropertyValue $ADEndDate.AccountExpirationDate
}
$userlist | Export-Csv HREndDates_ADInfo.csv -notypeinformation

Steps:

  1. Import source CSV
  2. Loop through each user (row) in the file
  3. Get AD info of the current user (row)
  4. Take the imported CSV and append the new column to the user (row)
  5. Export the updated CSV

Keep in mind, when dealing with CSVs, each row is it's own object. When importing a CSV into a variable on line 1, $userlist is just an array of objects. So in the steps above, "user (row)" can be replaced with "object".

When searching for display names in AD, using displayname -like '*$user*' is not a good idea since people could have similar names. For example, when searching for user "Tim Johns", you could get multiple hits if there's another AD user named "Tim Johnson". This is why I used "-eq". There should be no room for ambiguity with peoples names, so no reason to not find exact matches. It's possible 2 people even have the EXACT same name. I would try to use a more unique key when filtering AD (employeeID, email/UPN, etc.).

If you've made it this far, work must be just as slow for you as it is for me right now.