2015年3月4日 星期三

如何使用VB.NET撰寫「在Exchange 2010上建立信箱」的程式碼?

之前花了一些時間找,整理之後把它貼上來。
先說明一下,如果要用以下的程式碼來建信箱的話,請記得要先在AD中建帳號,之後才能用這段程式碼來建信箱。

'記得在程式最前面要參考這三個
Imports System.Management.Automation
Imports System.Management.Automation.Runspaces
Imports System.Management.Automation.Remoting

Public Function create_Mailbox(ByVal usrAccount As String, ByVal DBName As String, Optional ) As Boolean
    Dim enable_success As Boolean = True  '用來確認是否已經完成信箱建立的工作的布林值
    Dim newCred As PSCredential = Nothing '在建立遠端Runspace的認證資訊。設成nothing的話,就是使用現在登入者的認證資訊
    
    Dim connectionInfo As New WSManConnectionInfo(New Uri("http://yourserver.local/powershell?serializationLevel=Full"),"http://schemas.microsoft.com/powershell/Microsoft.Exchange", newCred) '建立遠端Runspace的連線資訊(PowerShell 2.0導入的新功能)
    connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos '認證機制設為kerberos認證

    '使用連線資訊線來建立遠端伺服器的單一runspace
    Dim myRunspcae As Runspace = RunspaceFactory.CreateRunspace(connectionInfo)
    '建立PowerShell物件 
    Dim myPowershell As PowerShell = PowerShell.Create() 

    Dim domainUser As String
    domainUser = "yourdomain\" + Trim(usrAccount)

    '建立PowerShell命令(用來啟用某個帳號的信箱),以下的指令組合之後就是 Enable-Mailbox -Identity "domain\usrAccount" -Alias "userAccount" -Database "DBName" )
    Dim myCommand As New PSCommand()
    
    myCommand.AddCommand("Enable-Mailbox")
    myCommand.AddParameter("Identity", domainUser)
    myCommand.AddParameter("Alias", usrAccount)
    myCommand.AddParameter("Database", DBName)
  
    myPowershell.Commands = myCommand
    Dim cmdResult As ICollection(Of PSObject) = Nothing
    Try
        myRunspcae.Open()
        myPowershell.Runspace = myRunspcae
        cmdResult = myPowershell.Invoke()

    Catch ex As Exception
        Dim errStr As String = ex.InnerException.ToString()
        enable_success = False
    Finally
        myRunspcae.Dispose()
        myRunspcae = Nothing

        myPowershell.Dispose()
        myPowershell = Nothing
    End Try

    Return enable_success

End Function

沒有留言:

張貼留言