c# - Powershell 和 C# 中的交换

标签 c# powershell exchange-server

我在 C# 中有以下代码,用于通过 powershell 进行连接以进行交换。

以下代码工作正常,但是我还需要一个命令才能使用交换 cmdlet。

这是我现在的代码。

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

PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", new Uri("https://ps.outlook.com/powershell/"));
command.AddParameter("Credential", creds);
command.AddParameter("Authentication", "Basic");
command.AddParameter("AllowRedirection");

powershell.Commands = command;

try
{
    runspace.Open();
    powershell.Runspace = runspace;

    Collection<PSObject> commandResults = powershell.Invoke();

    StringBuilder sb = new StringBuilder();

    foreach (PSObject ps in commandResults)
    {
        sb.AppendLine(ps.ToString());
    }

    sb.AppendLine();

    lbl.Text += sb.ToString();
}
finally
{
    // dispose the runspace and enable garbage collection
    runspace.Dispose();
    runspace = null;
    // Finally dispose the powershell and set all variables to null to free
    // up any resources.
    powershell.Dispose();
    powershell = null;
}

我的问题是我仍然需要运行命令 import-pssession $session 其中 $session 是我第一个命令的输出。但是我不确定如何将该输出声明为变量 $session 或类似的东西:

 PSCommand command = new PSCommand();
 command.AddCommand("Import-PSSession");
 command.AddParameter("Session", #Not sure how to put session info which is what the first command produces into here.);

最佳答案

您可以尝试使用创建远程运行空间来代替,下面给出了一个示例。可以引用以下文章http://msdn.microsoft.com/en-us/library/windows/desktop/ee706560(v=vs.85).aspx .

string schemaURI = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";
Uri connectTo = new Uri("https://ps.outlook.com/powershell/");
PSCredential credential = new PSCredential(user,secureStringPassword ); // the password must be of type SecureString
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(connectTo,schemaURI, credential);
connectionInfo.MaximumConnectionRedirectionCount = 5;
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

try
{
    Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo);
    remoteRunspace.Open();
}
catch(Exception e)
{
    //Handle error 
}

关于c# - Powershell 和 C# 中的交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10566603/

相关文章:

xml - 交换 : Find items in EWS conversation using XML request?

c# - “不存在数据时读取无效”错误

c# - 是否有必要释放从 C# 接收到的 C++ 字符串的内存?

tfs - 如何使用 PowerShell 批量重命名文件?

powershell - 函数输出类型

c# 可以将登录凭据(非显式)与 wsmanconnectioninfo 一起使用吗?

c# - 用于查找最近的前一个兄弟的 XPath 语句

c# - 绑定(bind)一个 [Serializable] 类的 ASP.Net MVC 模型

powershell - Azure DNS 中的通配符和裸 CNAME 记录

zend-framework - 使用 Zend_Mail 通过 Exchange Server 发送 SMTP 电子邮件 - 如何诊断这些错误