Share via

Getting an error "object reference not set to an instance of an object"

Soumyadeep Bhattacharya 21 Reputation points
2020-10-31T22:49:46.187+00:00

Hello All,

I am tasked to write a script in my organization to pull the country details of 5000+ users residing in various child domains under a forest. (Given their mail IDs).I have wrote the below script :

$users = Get-content user.txt
Foreach($user in $users){
Get-aduser -filter {mail -like $user} -server <my DC's fqdn>:3268 -properties * | select name, co | Export-csv country.csv -append

This script works fine for 98% of the mail IDs and i get a correct output regarding their country attribute. However for a handful of the mail IDs this does not work and give the above alert. I checked in AD these users are correctly created however the script is not able to pull details for only these users however the scripts runs fine for the majority of others.

I am new to powershell, so apologies for any silly question. Please Help me why the error is popping only for few users

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

3 answers

Sort by: Most helpful
  1. Rich Matheisen 48,116 Reputation points
    2020-11-01T02:36:37.007+00:00

    It never hurts to some data validation before using what comes from a file. Try this:

    Get-content user.txt |
        Foreach-Object {
            If ($_.Trim().Length -gt 3){
                $user = $_.Trim()
                Get-aduser -filter {mail -like $user} -server My-GC-fqdn:3268 -properties * | 
                    Select-Object name, co
            }
        } | Export-csv country.csv -NoTypeInfo
    

    Using the pipeline eliminates the need for the "-append" on the Export-CSV, too.

    Was this answer helpful?

    0 comments No comments

  2. Soumyadeep Bhattacharya 21 Reputation points
    2020-10-31T23:47:52.67+00:00

    Thanks for your response. No, the error disappears now, but all attributes are listing.

    Was this answer helpful?

    0 comments No comments

  3. Andreas Baumgarten 132.1K Reputation points MVP Volunteer Moderator
    2020-10-31T23:02:00.743+00:00

    if you just run this part of the script the error is popping up up as well?

    $users = Get-content user.txt
    Foreach($user in $users){
    Get-aduser -filter {mail -like $user} -server <my DC's fqdn>:3268 -properties *
    

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.