Get-ADUser Return Value for None Existence User

Ronald Seow 206 Reputation points
2020-08-19T00:28:15.533+00:00

Good morning!

I'm very new to Powershell scripting so please give me your utmost support whenever possible. Thank you in advance.

Scenario
I have been trying to work on a condition based on the result of Get-ADUser -Identity <Input>. Whenever I use that statement for an none existence user account, it will always be the default error message. I need to have it return a certain value be it True/False, 1/0 or anything else so that I can use the result from that statement to perform my task.

Can anyone please advise?

Thank you once again and best regards.
Ronald

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,453 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,511 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 46,556 Reputation points
    2020-08-19T02:29:02.577+00:00

    Wrap the cmdlet in a Try/Catch:

    Try{
        Get-ADUser -Identity xxxxx -ErrorAction STOP
        # code goes here for a successful execution
    }
    Catch{
        # code goes here for a failed attempt
    }
    
    1 person found this answer helpful.
    0 comments No comments

  2. SChalakov 10,381 Reputation points MVP
    2020-08-19T08:15:39.15+00:00

    Hi,
    besides what @Rich Matheisen suggested you can always do the following:

    if ( Get-ADUser -Identity <Input>) {  
     #True (1)  
     } else {  
    #False (0)  
    }  
    

    although I find the try and catch approach better.

    =========================================================

    Please don't forget to "Accept Answer" and upvote if the response helped you.
    Stoyan

    0 comments No comments

Your answer

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