System.Management.Automation错误访问被拒绝

时间:2017-02-08 07:57:30

标签: c# powershell exchange-server

System.Management.Automation类我使用c#PowerShell交换程序访问服务器,增加电子邮件帐户的任务,拒绝程序错误访问;

<pre><code>
 PSCredential credentials = new PSCredential(UserName, ssRunasPassword);
              //ExchangeUri=ExUri
                WSManConnectionInfo connectionInfo = new WSManConnectionInfo(ExchangeUri, "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credentials);
                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

                Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
                runspace.Open();
</code></pre>

1 个答案:

答案 0 :(得分:0)

嗯..访问被拒绝错误非常简单。我稍微修改了你的代码:

        string username = @"domain\username";
        string password = "pass";
        SecureString securePassword = new SecureString();
        foreach (char c in password)
        {
            securePassword.AppendChar(c);
        }
        securePassword.MakeReadOnly();

        PSCredential credentials = new PSCredential(username, securePassword);
        //ExchangeUri=ExUri
        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(ExUri), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credentials);
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

        Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
        runspace.Open();

如果这不起作用,您可以尝试通过PowerShell建立远程会话,看看您是否真的有权访问该服务器。