CodexBloom - Programming Q&A Platform

PowerShell 7.3 - guide with Retrieving Active Directory User Properties Using Get-ADUser in a Loop

πŸ‘€ Views: 21 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
powershell active-directory get-aduser PowerShell

I'm confused about I've encountered a strange issue with I'm working with a question while trying to retrieve specific properties of Active Directory users using `Get-ADUser` in a loop... The goal is to get the `Name`, `EmailAddress`, and `LastLogonDate` for a list of users defined in a CSV file. However, I’m working with an behavior when trying to access the `LastLogonDate` property. Here's the code I have so far: ```powershell # Importing users from CSV file $users = Import-Csv -Path 'C:\path\to\users.csv' # Looping through each user in the CSV foreach ($user in $users) { try { # Attempting to retrieve user information from Active Directory $userInfo = Get-ADUser -Identity $user.Username -Properties Name, EmailAddress, LastLogonDate Write-Output "User: $($userInfo.Name), Email: $($userInfo.EmailAddress), Last Logon: $($userInfo.LastLogonDate)" } catch { Write-behavior "behavior retrieving user $($user.Username): $_" } } ``` When I run this script, I get an behavior that says `Get-ADUser : want to bind parameter 'Identity' to the target. Exception setting "Identity": "The username or domain is not found."` sometimes, even though the usernames are correct. I've ensured that the usernames in the CSV match the ones in AD. Additionally, I'm not sure if `LastLogonDate` is populated for all users or if there’s a specific condition under which it may return null or cause an exception. How can I handle cases where the property might not exist? Is there a more reliable way to retrieve this information without causing the script to unexpected result? Any advice or best practices for dealing with user properties in this manner would be greatly appreciated! For reference, this is a production mobile app. Any examples would be super helpful.