If you’d need to find out whether a given Active Directory user exists, and provided you have installed the ActiveDirectory PowerShell module which is part of RSAT (Remote Server Administration Toolkit), here is a clever way:
@(Get-ADUser -LDAPFilter "(samaccountname=$SAMAccountName)").Count -ne 0
You can adjust the LDAP query to check for users based on other attributes as well.
ReTweet this Tip!
I'm all for using the ActiveDirectory module, but some organizations (like mine) do not permit remoting into DCs to proxy these cmdlets.
This is why I leverage the native .NET classes when on a machine that does not have the ActiveDirectory module installed. Unless I am mistaken, these are not legacy classes (you seem to imply that the class/methods have been deprecated)
Sure you can use the legacy way, but you can also do this without installing RSTAsimply by using a Implicit PSRemote session to any DC in the enterprise and proxy the AD cmdlets
Use PowerShell Active Directory Cmdlets Without Installing Any Software'blogs.technet.microsoft.com/heyscriptingguy/2011/10/04/use-powershell-active-directory-cmdlets-without-installing-any-software'
This can be done without installing RSAT ...
Search by NT Id (in xxx.yyy.com domain):
$LDAPFilter = 'LDAP://DC=xxx,DC=yyy,DC=com'
$Searcher.SearchRoot = $LDAPFilter
$Searcher.Filter = "(&(objectCategory=person)(anr=$NTId))"
Search by user name (in xxx.yyy.com domain):
$Searcher.Filter = "(&(objectCategory=person)(name=$UserName))"
Both options allow for wildcards (*)
This is a clear example on when the results of a cmdlet (Get-ADUSER)
'MUST **MUST** must'
be explicitly converted to an array with @(), as the single object returned (or $null) without it will be a single object, never an array, and the .COUNT property will never exist, and you'll get $Null ( or better, an error if using Strict Mode), but never an 1.
Since PowerShell v3, many people wrongly think they don't need to understand this fact, as the .Count property is appended automagically... but that does not happen always (as in this case), and only the .COUNT property is added, not all the members for a real array.
In short : Always use @() for the result of a pipeline if you are going to consider it as an array later.