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 ha
If "runspace" doesn't exist, that explains why the Get-Mailbox command is failing. Rather than managing a runspace, you could create a PowerShell instance in your initConnection method and use it wherever needed. Note this is shown with native code rather than a script.
ps = PowerShell.Create();
Set the execution policy.
ps.ClearCommands()
.AddCommand("Set-ExecutionPolicy")
.AddParameter("Scope", "Process")
.AddParameter("ExecutionPolicy", "Unrestricted")
.AddParameter("Confirm", false)
.AddParameter("Force", true)
.Invoke();
Create the credentials. Note that you should not need to call Get-Credential.
SecureString pass;
var creds = new PSCredential(username, pass);
Create and import a session.
var newSession = ps.ClearCommands()
.AddCommand("New-PSSession")
.AddParameter("ConfigurationName", "Microsoft.Exchange")
.AddParameter("ConnectionUri", "https://ps.outlook.com/powershell/")
.AddParameter("Credential", creds)
.AddParameter("Authentication", "Basic")
.AddParameter("AllowRedirection", true)
.Invoke();
var session = newSession[0];
var import = ps.ClearCommands()
.AddCommand("Import-PSSession")
.AddParameter("Session", session)
.Invoke();
ps.ClearCommands() is an extension method, added so it can be chained with AddCommand(), AddParameter(), etc:
public static PowerShell ClearCommands(this PowerShell ps)
{
if (ps.Commands != null)
ps.Commands.Clear();
return ps;
}
Use it in Get_Mailboxes()
protected void Get_Mailboxes(object sender, EventArgs e) {
var commandResults = ps.ClearCommands().AddCommand("Get-Mailbox").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();
}
When you close the app, or somewhere appropriate:
ps.ClearCommands()
.AddCommand("Get-PSSession")
.AddCommand("Remove-PSSession")
.Invoke();
ps.Dispose();
You have to add the Exchange snap-in to your runspace. Take a look at Exchange for developers.