Link to home
Start Free TrialLog in
Avatar of bsharath
bsharathFlag for India

asked on

Find Disabled users with mailbox.

Hi,

I got this script .What i need is to get the results to a file.This shows the results with popup's

' List all disabled users with a mailbox enabled, reporttheir login name, title manager, description
' and other mailbox information. At the end it gives the total number of disabled users, how many of
' them have mailbox, and how much the total size of those mailboxes.
' Created by Edward Aractingi 01/10/2006 http://edward.aractingi.net
On Error Resume Next
Dim intDisabledTotal, intDisabledWithMailboxTotal,strManager,intMailboxSize,strUserDisplayName,strLDAP
'The following is needed to write the mailboxes DNs to text file for use with exmerge to export them to PST files
strOutputFile = "c:\scripts\DisabledUsersWithMailbox.txt"
strLDAP = "'LDAP://dc=development,dc=group,dc=co,dc=uk'"
Const ForAppending = 1
Set objDictionary = CreateObject("Scripting.Dictionary")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.OpenTextFile(strOutputFile, ForAppending, True)
objLogFile.WriteLine ("##################################")
objLogFile.WriteLine ("### Script run at "& Now & " ###")

'Connect to AD
Const ADS_SCOPE_SUBTREE = 2
Const ADS_UF_ACCOUNTDISABLE  = 2 ' used to determine if the account is disabled
intTotal = 0
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 2000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

objCommand.CommandText = _
    "SELECT userAccountControl,sAMAccountName,displayName,title,manager,description" & _
    ",HomeMDB,msExchHomeServerName,legacyExchangeDN " & _
    "FROM "& strLDAP & " WHERE objectCategory='user' "
Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst
Do Until objRecordSet.EOF
intUAC=objRecordset.Fields("userAccountControl")

If (intUAC AND ADS_UF_ACCOUNTDISABLE)   Then ' if the account is not disabled, check to see if it has a mailbox
      intDisabledTotal = intDisabledTotal + 1
      If objRecordSet.Fields("HomeMDB").Value <> "" Then
            intDisabledWithMailboxTotal = intDisabledWithMailboxTotal + 1
          Wscript.Echo "----------------------------------------------"
          Wscript.Echo "User Name: " &  objRecordSet.Fields("displayName").Value
          Wscript.Echo "Account: " &  objRecordSet.Fields("sAMAccountName").Value
          Wscript.Echo "Title: " &  objRecordSet.Fields("title").Value
          'Converting the Manager's Distinguised name to simple name
                  strManager = objRecordSet.Fields("Manager").Value
                  strManager = Mid(objRecordSet.Fields("Manager").Value, 4, 330)
                  If not IsNull (strManager)then
                  strManagerA = Split(strManager, "," )
                  Wscript.Echo "Manager: " &  strManagerA(0)
                  End If
            'Find Exchange Server where the mailbox reside
            strServerName = objRecordSet.Fields("msExchHomeServerName").Value
            strServerNameA = Split(strServerName, "Servers/cn=")
            strServerName = strServerNameA(1)
            WScript.echo "Mailbox Server: " &   strServerName
            'loop through the description lines sinces it's an Array
            If Not IsNull(objRecordset.Fields("description").Value) Then
                  For Each varRecord In objRecordset.Fields("description").Value
                         WScript.Echo "Description: " &  varRecord & " "
                   Next
             End If
             'Run MailboxInfo Function on the user's mailbox
            strUserDisplayName =objRecordSet.Fields("displayName").Value
             intMailboxSize = intMailboxSize + CLng(MailboxInfo (strServerName,strUserDisplayName))
             objLogFile.WriteLine (objRecordset.Fields("legacyExchangeDN").Value)
             WScript.Echo objRecordset.Fields("legacyExchangeDN").Value
       End If
End If
    objRecordSet.MoveNext
Loop
Wscript.Echo "Total Number of disabled users is " & intDisabledTotal
Wscript.Echo "Total Number of those with active mailbox is " & intDisabledWithMailboxTotal
WScript.Echo "Total size of all mailboxes is " & intMailboxSize & " bytes." & FormatNumber(intMailboxSize /(2^30),1)& " KB."

' function mailboxinfo retrieve mailbox information from exchange server through WMI
Function MailboxInfo(strComputer, strUserDisplayName)
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & _
        "\ROOT\MicrosoftExchangeV2")
Dim colItems
Set colItems = objWMIService.ExecQuery _
    ("Select * from Exchange_Mailbox where MailboxDisplayName ='" & strUserDisplayName & "'")
If colItems Is Nothing Then
WScript.Echo "User "&strUserDisplayName&" not found on " & strComputer
Else
For Each objItem in colItems
    Wscript.Echo "Last logged-on user account: " & _
        objItem.LastLoggedOnUserAccount
    Wscript.Echo "Last logoff time: " & objItem.LastLogoffTime
    Wscript.Echo "Last logon time: " & objItem.LastLogonTime
    Wscript.Echo "Server name: " & objItem.ServerName
    Wscript.Echo "Size: " & objItem.Size
    Wscript.Echo "Storage group name: " & objItem.StorageGroupName
    Wscript.Echo "Store name: " & objItem.StoreName
    Wscript.Echo "Total items: " & objItem.TotalItems
    If IsNull (objItem.Size) Then
          MailboxInfo = 0
    Else
          'MailboxInfo = FormatNumber(objItem.Size/2^30,1)
          MailboxInfo = objItem.Size
    End If
Next
End If
End Function
'''''''''''''''''''''''''''''''''End of script'''''''''''''''''''''''''''''''''''''''''''''''''

Regards
Sharath
Avatar of kmotaweh
kmotaweh

try to run run the script from a command prompt and follow the script name by >c:\report.txt as an example that will parse the result to that file called report.txt
i think the script do that try to check this path "c:\scripts\DisabledUsersWithMailbox.txt"
Avatar of bsharath

ASKER

I check even this but it creates a fil.txt but nothing is stored there every thing detected pops up 1 by one.

---------------------------
Windows Script Host
---------------------------
User Name: Waseem Shahid
---------------------------
OK  
---------------------------


---------------------------
Windows Script Host
---------------------------
Title: Product Delivery Specialist
---------------------------
OK  
---------------------------

have you tried the first solution
Yes i even tried that but still pop up the data as i posted.
' This VBScript code finds all disabled user accounts in a domain.

' ---------------------------------------------------------------
' From the book "Active Directory Cookbook" by Robbie Allen
' ISBN: 0-596-00466-4
' ---------------------------------------------------------------

' ------ SCRIPT CONFIGURATION ------
strDomainDN = "<DomainDN>"    ' e.g. dc=rallencorp,dc=com
' ------ END CONFIGURATION ---------

strBase   =  "<LDAP://" & strDomainDN & ">;"
strFilter = "(&(objectclass=user)(objectcategory=person)" & _
            "(useraccountcontrol:1.2.840.113556.1.4.803:=2));"
strAttrs  = "name;"
strScope  = "subtree"

set objConn = CreateObject("ADODB.Connection")
objConn.Provider = "ADsDSOObject"
objConn.Open "Active Directory Provider"
set objRS = objConn.Execute(strBase & strFilter & strAttrs & strScope)
objRS.MoveFirst
while Not objRS.EOF
    Wscript.Echo objRS.Fields(0).Value
    objRS.MoveNext
wend




or


Summary: In this example we will use a customer AD query to search for disabled accounts with mailboxes.


Example 1.


In this example we will perform a custome AD search using Active Directory Users and Computers


1. Open Active Directory Users and Computers and click the find icon

2. In the "Find" drop down menu, select custom search and click the advanced tab

3. Paste the following in the white pane:

((&UserAccountControl:1.2.840.113556.1.4.803:=2)(msExchHomeServerName=*)(objectClass=User))



This will enumerate all disabled accounts with mailboxes. From here you can delete all the mailboxes by selecting the first user and scolling down to the bottom of the list and selecting the last user by shift + left click. Then right click the list, Exchange tasks and delete mailbox.



To perform a search of a single server:


((&UserAccountControl:1.2.840.113556.1.4.803:=2)(msExchHomeServerName=/O=Domain/OU=MyOU/cn=Configuration
/cn=Servers/cn=Exservername)(objectClass=User))

Click find.


To obtain the full dn of your msExchHomeServerName attribute, you can find this in ADSIEdit.

1. Go to start run, type adsiedit.msc (part of windows server support tools)

2. Expand Domain, this should resemble your OU structure. Locate a user, right click a user cn=my user and select properties.

3. Look for attribute msExchHomeServerName and double click. Copy this string and paste it in the above Ldap query.


Other tricks:


Find disabled accounts with mailboxes that are not hidden in the GAL.


((&UserAccountControl:1.2.840.113556.1.4.803:=2)(msExchHomeServerName=*)(!msExchHideFromAddressLists=TRUE)(objectClass=User))


Best practices:


Ensure that you have deleted Mailbox retention configured to ensure that these mailboxes can be recovered in a swift manner. To configure mailbox retention, open Exchange System Manger, locate your mailbox store, properties limits tab.

From (http://msexchangetips.blogspot.com/2007/06/exchange-find-disabled-accounts-with.html)
FOTC
How can i find all Disabled users who dont have a mailbox...
i will try to use dsquery and make the script for you , i will try it and come back to you
Ok thanks...
dsget user -disabled -email  >c:\test.txt


try this command it will take a long time and it will a text file called test.txt on your c drive , the result is the disabled users with an e-mail address wich should equal a mailbox , try the result and tell me if this helped you or not
kmotaweh

This file is been running from past 6 hrs but still no results
stop it i will try something else and i will back to you
ok thanks...
Any help.Just a reminder...
Any help....
Any help...
Any help....
ASKER CERTIFIED SOLUTION
Avatar of RobSampson
RobSampson
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
RobSampson

This is outputting the data on the cmd screen.

How can i get it to a csv file...
Got it Rob thanks...
Do you want it all output to the file, exactly as you see it on the command prompt?  It will take me a while to go through that....basically it involves changing each WScript.Echo statement to objLogFile.Write

I don't think you want it exactly as it is output on screen, or, if you do, then you probably want it horizontal, rather than vertical, so I'll re-arrange it.....

Regards,

Rob.
Oh, OK, never mind about my question then..........next......LOL!
Rob this sound great i shall raise a new post if you can get all the data as horizontal..

Please let me know when you are done.

Sharath, see if this writes the output horizontally to a CSV file:
'===================
If LCase(Right(Wscript.FullName, 11)) = "wscript.exe" Then
    strPath = Wscript.ScriptFullName
    strCommand = "%comspec% /c cscript  """ & strPath & """"
    Set objShell = CreateObject("Wscript.Shell")
    objShell.Run(strCommand), 1, True
    Wscript.Quit
End If

' List all disabled users with a mailbox enabled, reporttheir login name, title manager, description
' and other mailbox information. At the end it gives the total number of disabled users, how many of
' them have mailbox, and how much the total size of those mailboxes.
' Created by Edward Aractingi 01/10/2006 http://edward.aractingi.net
On Error Resume Next
Dim intDisabledTotal, intDisabledWithMailboxTotal,strManager,intMailboxSize,strUserDisplayName,strLDAP
'The following is needed to write the mailboxes DNs to text file for use with exmerge to export them to PST files
strOutputFile = "DisabledUsersWithMailbox.CSV"
strLDAP = "'LDAP://dc=maroondah,dc=local'"
Const ForAppending = 8
Set objDictionary = CreateObject("Scripting.Dictionary")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objLogFile = objFSO.CreateTextFile(strOutputFile, True)
objLogFile.Write """Display Name"",""Login Name"",""Title"",""Manager"",""Mail Server"",""Description"",""LegacyExchangeDN"""

'Connect to AD
Const ADS_SCOPE_SUBTREE = 2
Const ADS_UF_ACCOUNTDISABLE  = 2 ' used to determine if the account is disabled
intTotal = 0
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 2000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

objCommand.CommandText = _
    "SELECT userAccountControl,sAMAccountName,displayName,title,manager,description" & _
    ",HomeMDB,msExchHomeServerName,legacyExchangeDN" & _
    " FROM "& strLDAP & " WHERE objectCategory='user' "

objCommand.CommandText = _
    "SELECT userAccountControl,sAMAccountName,displayName,title,manager,description" & _
    " FROM "& strLDAP & " WHERE objectCategory='person' AND objectClass='user'"

Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst
Do Until objRecordSet.EOF
intUAC=objRecordset.Fields("userAccountControl")
      If (intUAC AND ADS_UF_ACCOUNTDISABLE)   Then ' if the account is not disabled, check to see if it has a mailbox
            intDisabledTotal = intDisabledTotal + 1
            If objRecordSet.Fields("HomeMDB").Value <> "" Then
                  intDisabledWithMailboxTotal = intDisabledWithMailboxTotal + 1
                Wscript.Echo "----------------------------------------------"
                Wscript.Echo "User Name: " &  objRecordSet.Fields("displayName").Value
                Wscript.Echo "Account: " &  objRecordSet.Fields("sAMAccountName").Value
                objLogFile.Write VbCrLf & """" & objRecordSet.Fields("displayName").Value & ""","
                objLogFile.Write """" & objRecordSet.Fields("sAMAccountName").Value & ""","
                Wscript.Echo "Title: " &  objRecordSet.Fields("title").Value
                objLogFile.Write """" & objRecordSet.Fields("Title").Value & ""","
                'Converting the Manager's Distinguised name to simple name
                        strManager = objRecordSet.Fields("Manager").Value
                        strManager = Mid(objRecordSet.Fields("Manager").Value, 4, 330)
                        If not IsNull (strManager)then
                              strManagerA = Split(strManager, "," )
                              Wscript.Echo "Manager: " &  strManagerA(0)
                              objLogFile.Write """" & strManagerA(0) & ""","
                        Else
                              objLogFile.Write """"","                              
                        End If
                  'Find Exchange Server where the mailbox reside
                  strServerName = objRecordSet.Fields("msExchHomeServerName").Value
                  strServerNameA = Split(strServerName, "Servers/cn=")
                  strServerName = Trim(strServerNameA(1))
                  WScript.echo "Mailbox Server: " &   strServerName
                  objLogFile.Write """" & strServerName & ""","
                  'loop through the description lines sinces it's an Array
                  If Not IsNull(objRecordset.Fields("description").Value) Then
                        For Each varRecord In objRecordset.Fields("description").Value
                               WScript.Echo "Description: " &  varRecord & " "
                               objLogFile.Write """" & varRecord & ""","
                        Next
                  Else
                        objLogFile.Write """"","
                  End If
                   'Run MailboxInfo Function on the user's mailbox
                  strUserDisplayName =objRecordSet.Fields("displayName").Value
                   intMailboxSize = intMailboxSize + CLng(MailboxInfo (strServerName,strUserDisplayName))
                   WScript.Echo objRecordset.Fields("legacyExchangeDN").Value
                   objLogFile.Write """" & objRecordSet.Fields("legacyExchangeDN").Value & """"
             End If
      End If
    objRecordSet.MoveNext
Loop
WScript.Echo ""
WScript.Echo ""
Wscript.Echo "----------------------------------------------"
WScript.Echo ""
Wscript.Echo "Total Number of disabled users is " & intDisabledTotal
Wscript.Echo "Total Number of those with active mailbox is " & intDisabledWithMailboxTotal
WScript.Echo "Total size of all mailboxes is " & intMailboxSize & " bytes." & FormatNumber(intMailboxSize /(2^30),1)& " KB."
objLogFile.WriteLine
objLogFile.WriteLine
objLogFile.WriteLine
objLogFile.WriteLine "Total Number of disabled users is " & intDisabledTotal
objLogFile.WriteLine "Total Number of those with active mailbox is " & intDisabledWithMailboxTotal
objLogFile.WriteLine "Total size of all mailboxes is " & intMailboxSize & " bytes." & FormatNumber(intMailboxSize /(2^30),1)& " KB."


objLogFile.Close
Set objLogFile = Nothing

MsgBox "Done"

' function mailboxinfo retrieve mailbox information from exchange server through WMI
Function MailboxInfo(strComputer, strUserDisplayName)
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & _
        "\ROOT\MicrosoftExchangeV2")
Dim colItems
Set colItems = objWMIService.ExecQuery _
    ("Select * from Exchange_Mailbox where MailboxDisplayName ='" & strUserDisplayName & "'")
If colItems Is Nothing Then
WScript.Echo "User "&strUserDisplayName&" not found on " & strComputer
Else
For Each objItem in colItems
    Wscript.Echo "Last logged-on user account: " & _
        objItem.LastLoggedOnUserAccount
    Wscript.Echo "Last logoff time: " & objItem.LastLogoffTime
    Wscript.Echo "Last logon time: " & objItem.LastLogonTime
    Wscript.Echo "Server name: " & objItem.ServerName
    Wscript.Echo "Size: " & objItem.Size
    Wscript.Echo "Storage group name: " & objItem.StorageGroupName
    Wscript.Echo "Store name: " & objItem.StoreName
    Wscript.Echo "Total items: " & objItem.TotalItems
    If IsNull (objItem.Size) Then
          MailboxInfo = 0
    Else
          'MailboxInfo = FormatNumber(objItem.Size/2^30,1)
          MailboxInfo = objItem.Size
    End If
Next
End If
End Function
'===================

Regards,

Rob.
Ooops, you'll have to change the LDAP domain name....

Rob.
Rob i get this.

Total Number of disabled users is 180
Total Number of those with active mailbox is 180
Total size of all mailboxes is  bytes.0.0 KB.
I dont get this these details LegacyExchangeDN


Oh sorry, I put in these three lines
objCommand.CommandText = _
    "SELECT userAccountControl,sAMAccountName,displayName,title,manager,description" & _
    " FROM "& strLDAP & " WHERE objectCategory='person' AND objectClass='user'"

for a testing query, please comment those out and try again.  The query directly above that is the one you need.

Regards,

Rob.
Thanks a lot Rob....

I have raise a Q for this solution...Please put in the code here

https://www.experts-exchange.com/questions/22793516/Need-help-on-formatting-the-script.html