Richard
Tue Sep 16 19:30:24 CDT 2003
Gar wrote:
> Does anyone know how to use vbs or wsh scripting to get the AD
> username for the currently logged in user? What I am trying to do is
> write a logon script that looks at the current user's group
> memberships to map printers. I do not know how to retrieve the
> username of the person that is logged in. I have the rest of the
> script but with the username hard coded as seen below:
>
> Set objUser = GetObject _
> ("LDAP://cn=MyerKen,ou=Management,dc=NA,dc=fabrikam,dc=com")
Hi,
If all of the clients are W2k or above, you can use the ADSystemInfo object.
For example:
Set objSysInfo = CreateObject("ADSystemInfo")
strUserDN = objSysInfo.userName
Set objUser = GetObject("LDAP://" & strUserDN)
If the clients are NT or above, you can retrieve the NT logon name from the
WshNetwork object, then use the NameTranslate object to convert this to the
Distinguished Name. If any clients are Win9x, you can still do this, but a
loop is required, as shown below. My example also retrieves the domain
information programmatically, rather than relying on hard coding:
Set objNetwork = CreateObject("Wscript.Network")
' Loop required for Win9x clients during logon.
strNTName = ""
On Error Resume Next
Err.Clear
Do While strNTName = ""
strNTName = objNetwork.UserName
Err.Clear
If Wscript.Version > 5 Then
Wscript.Sleep 100
End If
Loop
On Error GoTo 0
' Determine DNS domain name from RootDSE object.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
' Use the NameTranslate object to find the NetBIOS domain name from the
' DNS domain name.
Set objTrans = CreateObject("NameTranslate")
objTrans.Init 3, strDNSDomain
objTrans.Set 1, strDNSDomain
strNetBIOSDomain = objTrans.Get(3)
' Remove trailing backslash.
strNetBIOSDomain = Left(strNetBIOSDomain, Len(strNetBIOSDomain) - 1)
' Use the NameTranslate object to convert the NT user name to the
' Distinguished Name required for the LDAP provider.
objTrans.Init 1, strNetBIOSDomain
objTrans.Set 3, strNetBIOSDomain & "\" & strNTName
strUserDN = objTrans.Get(1)
' Bind to the user object in Active Directory with the LDAP provider.
Set objUser = GetObject("LDAP://" & strUserDN)
Some example logon scripts demonstrating all of this, plus determining group
membership to map drives and connect printers, are at the link below:
http://www.rlmueller.net/freecode2.htm
And, examples of functions to test for group membership are at this link:
http://www.rlmueller.net/freecode1.htm
The method you select depends on the client OS's supported, whether you have
nested group, whether you have cross-domain groups, etc.
--
Richard
Microsoft MVP Scripting and ADSI
HilltopLab web site -
http://www.rlmueller.net
--