开发者

VB.NET Powershell piping results from one command to another

I currently have an ASP.NET programming creating a Powershell CmdLet to create a mailbox in exchange.

The issue I'm having is sometimes is fails to create the mailbox because "it can't find" the exchange database I am specifying.

So what I'm trying to do is run a Get-Mailbox and then pipe the results to an Enable-Mailbox command.

Below is the code I am using to do it:

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

This is the command to get the mailbox:

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

开发者_开发百科    cmd.Parameters.Add("Database", UserDatabase)

    Return cmd
End Function

Command to create the mailbox:

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

Code to execute all the powershell commands:

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


It turns out the issue was to do with the user being used to run the application pool did not have permissions to access the Exchange databases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜