In PowerShell (PS) script or. NET Active Directory programming often requires checking for the presence of an ad object, but neither the PS ad module nor the current version of the framework has yet provided a direct method. Based on the experience of writing ad scripts in recent years, this article summarizes the following:
The first method is to invoke the ADSI static method exists (), which uses a query that could be the winnt of the last century provider or LDAP, using the following syntax:
[Adsi]::exists ("Winnt://domainname/samaccountname");
[Adsi]::exists ("ldap://distinguishedname")
The advantage of using Winnt is that you can not care about the location of the object, because the NT time domain is a flat structure with no hierarchy and less keyboard input when used. However, both ADSI methods have one drawback, which returns True when the query object exists and returns COMException if it does not exist. You need to use the Try...catch structure to capture the false.
The second method is to use the dsquery command, which may be the system administrator feel more cordial method, this method needs to use the object type to query, such as User,group, ... Above PS 3.0 is I like to use (dsquery user-samid samaccountname). Count to determine the presence or not, the return value 1 just means that there is, and 0 means that it does not exist.
The third method is actually a programmer using the Directoryservices.directorysearcher class of the FindOne () method, the query is the standard LDAP query, its PS implementation resembles the following:
([Adsisearcher] ' (& (Objectclass=group) (Samaccountname=groupname)). FindOne ()
Above PS 3.0 can be the same as above, with the array of the Count property 1,0 to determine the existence or not.
The above summarizes the author used several methods, do not know if the spectator is still a better way, welcome message!
This article is from the "Powersheller Shell" blog, please be sure to keep this source http://powersheller.blog.51cto.com/4428055/1663160
PowerShell checks if the AD object exists