Check if a user or group exists in AD using PowerShell

Check if a user or group exists in AD using PowerShell

Q. How can I easily check if a user or group exists in AD using PowerShell?

A. The easiest way to check for a user or group in AD using PowerShell would be the following. Note it gets the object based on a simple filter and if the resulting object is null it means it was not found.

$userobj = Get-ADUser -LDAPFilter "(SAMAccountName=$username)"
$vlanobj = Get-ADGroup -LDAPFilter "(SAMAccountName=$vlangroupname)"

if ($userobj -eq $null) {"User not valid"}
if ($vlanobj -eq $null) {"VLAN not valid"}

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish