I'm trying to connect to connect to power-shell using .Net C#. I need to get details of mailbox, create new mailbox and delete existing mailbox.
I use "Get-Mailbox","New-Mailbox" & "Remove-Mailbox".
But when I invoke the command it throws me below error.
The term 'Get-Mailbox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,verify that the path is correct and try again.
I connecting to power-shell remotely.
What I have tried:
Runspace runspace = null;
string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
PSCredential remoteCredential = new PSCredential(@"userid", StringToSecureString("password"));
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "ip address",5985, "/wsman", shellUri, remoteCredential, 1 * 60 * 1000);
connectionInfo.OperationTimeout = 4 * 60 * 1000;
runspace = RunspaceFactory.CreateRunspace(connectionInfo);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
ps.Commands.AddCommand("Get-Mailbox");
ps.Commands.AddParameter("Identity", "user@domain.com");
var result = ps.Invoke();
foreach (PSObject res in result)
{
Console.WriteLine("{0,-25}1}",res.Members["DisplayName"].Value,res.Members["PrimarySMTPAddress"].Value);
}
}
runspace.Close();
runspace.Dispose();
And this
string shellUri = "http://schemas.microsoft.com/powershellMicrosoft.PowerShell";
PSCredential remoteCredential = new PSCredential(@"userid", StringToSecureString("password"));
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "ip address", 5985, "/wsman", shellUri, remoteCredential, 1 * 60 * 1000);
connectionInfo.OperationTimeout = 4 * 60 * 1000;
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;
runspace.Open();
Pipeline pipelineGetMailBox = runspace.CreatePipeline();
Command getMailBox = new Command("Get-Mailbox");
getMailBox.Parameters.Add("OrganizationalUnit", "OU Name");
getMailBox.Parameters.Add("Identity", "user@domain.com");
pipelineGetMailBox.Commands.Add(getMailBox);
Collection<PSObject> mailboxGetResult = pipelineGetMailBox.Invoke();
pipelineGetMailBox.Dispose();
runspace.Close();
runspace.Dispose();