Disable user exchange mailbox from AD using VB.NET

Hi Experts,
     
    I need to disable the exchange mailbox from AD using .NET ...

For this i am getting all the users in a listbox1 ...so when selected a user from the listbox and when i click on the button i need to disable the exchange Mailbox from AD....

For this i added the referances like CDOEXM and CDO

Please find the below code .....i am getting an error like "CDOEXM.IMailRecipient is unable to cast "...

can any one help me is there any better way to do this.....i really appriciate if any one suggest me in different way to disable the Exchange Mailbox from AD
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Try
            Dim UserName As String
            Dim objRecip As CDOEXM.IMailRecipient

            UserName = "CN=" + ListBox1.SelectedItem + "," + oupath

            Dim objuserpath As DirectoryEntry
            objuserpath = New DirectoryEntry("LDAP://" + UserName + "")

            objRecip = DirectCast(objuserpath, CDOEXM.IMailRecipient)
                       objRecip.MailDisable()
            objuserpath.CommitChanges()
        Catch ex As Exception
            MessageBox.Show(ex.Message + " " + ex.StackTrace)
        End Try



    End Sub

Open in new window

bobby010606Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

 
Hilal1924Commented:
If you are using Exchange 2007 and above , Use the following Command to disable it.
Disable-Mailbox john.smith@company.com

You can lso delete/disable mailbox via VbScript that is attached.
 
Hilal
 

VBScript'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' bajas.vbs 
' VBScript para dar de baja usuarios en el Active Directory desde un TXT
' Original Author Gustavo Riveros
' Version 1.0 - 3:35 PM Wednesday, February 08, 2006
' NOTE: EL SCRIPT Y EL "TXT CON LAS CUENTAS" DEBEN ESTAR EN EL MISMO DIRECTORIO PARA EL FUNCIONAMIENTO
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'On Error Resume Next
Option Explicit
'declaring variables...
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const ADS_UF_ACCOUNTDISABLE = 2

Dim strTxtFile, strOpenTextFile
Dim objRootDSE, strDomain
Dim WshShell, strCurrentDir
Dim objOpenFILE, objOpenTXTfile, strLine
Dim ObjConnection, ObjCommand, strConsultaLDAP
Dim objRecordSet, strADsPath, ObjUser, strEchoAttribute
Dim intUAC, strDescription
Dim ADS_SCOPE_SUBTREE

strTxtFile = "bajas.txt" 'please type your TXT file

WScript.Echo "================= START SCRIPT ================="

'obtain defaultNamingContext from W2K doamain
Set objRootDSE = GetObject("LDAP://rootDSE")
strDomain = "LDAP://" & objRootDSE.Get("defaultNamingContext")
Set objRootDSE = nothing

'obtain current directory a txt file...
Set WshShell = WScript.CreateObject("WScript.Shell")  
strCurrentDir = WshShell.CurrentDirectory
strOpenTextFile = strCurrentDir & "\" & strTxtFile
Set WshShell = nothing

'Open txt file
Set objOpenFILE = CreateObject("Scripting.FileSystemObject")
Set objOpenTXTfile = objOpenFILE.OpenTextFile(strOpenTextFile, 1)
Wscript.Echo "LDAP DOMAIN : " & strDomain
WScript.Echo "OPEN FILE   : " & strOpenTextFile
wscript.echo

subReadFile
destruction

Sub subReadFile() ' in this subroutine read line4line
	Do Until objOpenTXTfile.AtEndOfStream
		strLine = objOpenTXTfile.ReadLine
		fSearch(strLine)
		'WScript.Echo strLine
	Loop
	objOpenTXTfile.Close
End Sub

Sub destruction() 'sub for destroy variables...
	strTxtFile = 0
	strOpenTextFile = 0
	Set objRootDSE = Nothing
	strDomain = 0
	Set WshShell = Nothing
	strCurrentDir = 0
	Set objOpenFILE = Nothing
	Set objOpenTXTfile = Nothing
	strLine = 0
	WScript.Echo "================= END SCRIPT ================="
End Sub

Function fSearch(strBusqueda) 'function for search, retrieve and setting object in active directory
	Set objConnection = CreateObject("ADODB.Connection")
	objConnection.Provider = "ADsDSOObject"
	objConnection.Open "Active Directory Provider"
	Set objCommand = CreateObject("ADODB.Command")
	Set objCommand.ActiveConnection = objConnection
	objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
	objCommand.Properties("Cache Results") = False ' do not cache the result, it results in less memory requirements
    objCommand.Properties("Size Limit") = 1 ' Limit to 1 Result

	strConsultaLDAP = "<" & strDomain & ">;(&(ObjectClass=*)(displayName=" & strBusqueda & "));AdsPath,displayName;subTree"
	objCommand.CommandText = strConsultaLDAP
	Set objRecordSet = objCommand.Execute
	While Not objRecordSet.EOF
		strADsPath = objRecordSet.Fields("AdsPath")
		Set ObjUser = GetObject(strADsPath)
		strEchoAttribute = ObjUser.get ("sAMAccountName")
		WScript.Echo "setting user: " & strEchoAttribute
		strDescription = "BAJA 17202544 "& Now & " [x riverog]"
		intUAC = objUser.Get("userAccountControl")
		objUser.Put "userAccountControl", intUAC OR ADS_UF_ACCOUNTDISABLE
		ObjUser.Put "delivContLength", 1
		ObjUser.Put "submissionContLength", 1
		ObjUser.Put "mDBUseDefaults", false
		ObjUser.Put "mDBOverHardQuotaLimit", 1
		ObjUser.Put "mDBOverQuotaLimit", 1
		ObjUser.Put "mDBStorageQuota", 1
		ObjUser.Put "msExchHideFromAddressLists", true
		ObjUser.Put "description", strDescription
		ObjUser.SetInfo
		WScript.Echo "Account " & objUser.sAMAccountName & " disabled!"
		wscript.echo
		objRecordSet.MoveNext
	Wend
	Set ObjUser = nothing
	objConnection.Close
End Function

Open in new window

0

Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
 
Hilal1924Commented:
Here is a simpler script
I found it at:
http://www.scriptinganswers.com/forum2/forum_posts.asp?TID=2915
Hilal

$users = (c:\old_users.txt)foreach ($user in $users) { Disable-QADUser "$user" }
foreach ($user in (gc c:\old_users.txt)){(Get-QADUser $user).memberOf | Get-QADGroup | where {$_.name -notmatch '^users|domain users}
foreach ($user in $users) { Set-QADUser "$user" -oa @{'msExchHideFromAddressLists'=$True}}
foreach ($user in $users) { Move-QADObject "$user" -NewParentContainer 'domainname.com/disabled_users' }

Open in new window

0
 
bobby010606Author Commented:
soory i forget to mension i am working on exchange server 2003...will the 1st post code work on Exchange server 2003
0
Has Powershell sent you back into the Stone Age?

If managing Active Directory using Windows Powershell® is making you feel like you stepped back in time, you are not alone.  For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why.

 
Hilal1924Commented:
powershellcommand will not work but the vbscript will.

bol
Hilal
0
 
bobby010606Author Commented:
is there any other solution Hilal1924
0
 
Hilal1924Commented:
Yes Of course there are. What exactly do you need aprt from Disabling Mailbox.
 
1. Do you want to disable the user account ?
2. Do you want to delete the account as well ?
3. Do you need to disable this for many users or just a few ?
 
Hilal
0
 
bobby010606Author Commented:
i really appriciate about your previous post
i just need to disable Mailbox of the user account.....any .NEt script will work for me Hilal1924
0
 
bobby010606Author Commented:

Hilal any luck ...plz help me
0
 
Hilal1924Commented:
Again Sorry for the delay: By Disabling, do you mean just remove the access or delete the mailbox. Removing access would mean that they will not be able to log in via Outlook, Webmail, ActiveSync etc. While as Deleting will delete the entire Mailbox.
 
Hilal
0
 
bobby010606Author Commented:
Yaa i just want to remove the access the user should not able to log in via Outlook, Webmail, ActiveSync etc.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.