Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am using c# to send powershell commands interacting with exchange. I have a method called initconnection which sets up my connection to exchange.

I have another method that I call when I click a button that will send a command to powershell after the connection is established. However I am not able to continue the created connection. When I try to run a command it says the command is not found. More than likely because it doesn't have the exchange cmdlets.

 Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();


                runspace.Open();

                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript("Set-ExecutionPolicy Unrestricted -Scope process -Force;$password = ConvertTo-SecureString -AsPlainText -Force " + password + ";$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist " + username + ",$password;$LiveCred = Get-Credential -Credential $mycred; $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic –AllowRedirection; Import-PSSession $Session");
                // pipeline.Commands.Add("Out-String");


                pipeline.Invoke();
                mpeAdd.Hide();

This is the initconnection method that creates the connection.

 protected void Get_Mailboxes(object sender, EventArgs e) {




        PowerShell powershell = PowerShell.Create();
        PSCommand command = new PSCommand();
        command = new PSCommand();
        command.AddCommand("Get-Mailbox");


        powershell.Commands = command;
        powershell.Runspace = runspace; //also it says runsapce doesn't exist in this context
        Collection<PSObject> commandResults = powershell.Invoke();

        StringBuilder sb = new StringBuilder();

        ArrayList boxesarray = new ArrayList();

        foreach (PSObject ps in commandResults)
        {
            boxesarray.Add(ps.Properties["Alias"].Value.ToString());

        }

        boxes.DataSource = boxesarray;
        boxes.DataBind();

    }

This is my method I call when I click a button after the connection is create however it is not working.

share|improve this question

1 Answer

You have to add the Exchange snap-in to your runspace. Take a look here http://msdn.microsoft.com/en-us/library/exchange/bb332449(v=exchg.80).aspx

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.