7

#PSTip Validate if a user exists in Active Directory

Note: This tip requires PowerShell 3.0 or above.

[adsisearcher] is a PowerShell type adapter for DirectorySearcher .NET class. We can use this type adapter to perform queries against Active Directory Domain Services.

In this tip, we shall see how we can validate if a given user exists in AD or not. This is how we do it.

[bool]([adsisearcher]"samaccountname=username").FindOne()

This snippet returns True or False based on if the user exists or not.

Filed in: Columns, Tips and Tricks Tags: , ,

7 Responses to "#PSTip Validate if a user exists in Active Directory"

  1. Andy Xu says:

    If you have AD module loaded. the following work well.
    Get-ADUser -filter {samaccountname -eq “username”}

  2. Art Lewis says:

    That’s extremely useful. Thank you.

  3. Perry Harris says:

    This also seems to work in PowerShell 2.0 as well.

  4. Mark Kordelski says:

    This works well if the user’s domain is the same as the running user’s domain. However this does not yield valid results if the user to be validated is in a remote domain.
    Example:
    running user is CONTOSO\Administrator
    account to validate is CONTOSO\Mark
    [bool]([adsisearcher]”samaccountname=mark”).FindOne() returns True
    However, if:
    account to validate is WINGTIPTOYS\Mark
    [bool]([adsisearcher]”samaccountname=mark”).FindOne() returns True only if the CONTOSO domain has a “mark” account. It does not provide any indication of whether the domain WINGTIPTOYS has a “mark” account.

Leave a Reply

Submit Comment

© 2015 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: