Introduction
This VBScript is used to check if a user has an exchange mailbox. The result is the Errorlevel
variable which will be set. This script can be called in a command file. For example, you could run outlook only if the user has a mailbox.
Solution
The solution is to check if there is Exchange information in active directory for this user.
As you can see, the username (logonname
) is optional. In case you do not give the username, then the name will be taken from the environment variable USERNAME
.
In a command file (e.g. Logon script) it is sufficient to call this script and to check the
Errorlevel
.
REM *** Run Outlook when user has an exchange account ***
HasMailBox.vbs
If not errorlevel==1 outlook.exe
Change the Domain Controller information, replace MyMainDC
with the domain controller you want to query. (LDAP)
DCServer = "MyMainDC"
Dim ArgObj
Dim WshShell
Dim objEnv
Dim objUser
Dim objMailbox
Dim sUserLDAPName
Dim DCServer
Set ArgObj = WScript.Arguments
If ArgObj.Count < 1 Then
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objEnv = WshShell.Environment("PROCESS")
sUserName = objEnv("USERNAME")
else
sUserName = UCase(ArgObj(0))
End If
DCServer = "MyMainDC"
sUserLDAPName = QueryActiveDirectory(sUserName)
Set objUser = GetObject("LDAP://" & DCServer + "/" & sUserLDAPName)
Set objMailbox = objUser
If objMailbox.HomeMDB = "" Then
WScript.Quit 1
Else
WScript.Quit 0
End If
Public Function QueryActiveDirectory(sUserName)
Dim oAD
Dim oGlobalCatalog
Dim oRecordSet
Dim oConnection
Dim strADsPath
Dim strQuery
Dim strUPN
set oRecordSet = CreateObject("ADODB.Recordset")
set oConnection = CreateObject("ADODB.Connection")
Set oAD = GetObject("GC:")
For Each oGlobalCatalog In oAD
strADsPath = oGlobalCatalog.AdsPath
Next
oConnection.Provider = "ADsDSOObject"
oConnection.Open "ADs Provider"
strQuery = "<" & strADsPath & _
">;(&(objectClass=user)(objectCategory=person)(samaccountName=" & _
sUserName & "));userPrincipalName,cn,distinguishedName;subtree"
Set oRecordSet = oConnection.Execute(strQuery)
If oRecordSet.EOF And oRecordSet.BOF Then
QueryActiveDirectory = "Not Found"
Else
While Not oRecordSet.EOF
QueryActiveDirectory = oRecordSet.Fields("distinguishedName")
oRecordSet.MoveNext
Wend
End If
End Function