VB.NET Powershell管道从一个命令到另一个命令

时间:2010-12-08 02:06:52

标签: asp.net vb.net powershell

我目前有一个ASP.NET编程创建一个Powershell CmdLet来交换创建邮箱。

我遇到的问题有时是无法创建邮箱,因为“它无法找到”我指定的交换数据库。

所以我要做的是运行Get-Mailbox,然后将结果通过管道传输到Enable-Mailbox命令。

以下是我用来执行此操作的代码:

Public Sub CreateMailbox()

    Dim getMailbox As Command
    getMailbox = GetMailboxCommand()

    Dim createCommand As Command
    createCommand = GetCreateCommand()

    Dim results As String

    results = RunCommand(createCommand, getMailbox)

    Dim setCommand As Command
    setCommand = GetSetCommand()

    results = RunCommand(setCommand)

End Sub

这是获取邮箱的命令:

Private Function GetMailboxCommand() As Command
    Dim cmd As New Command("Get-Mailbox")

    cmd.Parameters.Add("Database", UserDatabase)

    Return cmd
End Function

创建邮箱的命令:

Private Function GetCreateCommand() As Command
    Dim cmd As New Command("Enable-Mailbox")

    cmd.Parameters.Add("Identity", DistinguishedName)
    cmd.Parameters.Add("Database")
    cmd.Parameters.Add("Alias", UserAlias)
    cmd.Parameters.Add("PrimarySmtpAddress", PrimarySMTP)

    Return cmd

End Function

执行所有powershell命令的代码:

Private Function RunCommand(ByVal createCommand As Command, ByVal getMailbox As Command) As String
    'Create Runspace configuration
    Dim rsConfig As RunspaceConfiguration
    rsConfig = RunspaceConfiguration.Create()

    Dim snapInException As PSSnapInException = Nothing
    Dim info As PSSnapInInfo
    info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", snapInException)

    Dim myRunSpace As Runspace
    myRunSpace = RunspaceFactory.CreateRunspace(rsConfig)
    myRunSpace.Open()

    Dim pipeLine As Pipeline
    pipeLine = myRunSpace.CreatePipeline()

    pipeLine.Commands.Add(getMailbox)
    pipeLine.Commands.Add(createCommand)

    pipeLine.Commands.Add("Out-String")

    Dim commandResults As Collection(Of PSObject)
    commandResults = pipeLine.Invoke()

    myRunSpace.Close()

    Dim sb As String = "Results: "
    For Each result As PSObject In commandResults
        sb &= result.ToString
    Next

    Return sb
End Function

1 个答案:

答案 0 :(得分:0)

事实证明问题与用于运行应用程序池的用户没有访问Exchange数据库的权限有关。