我想通过 C# 使用 powershell 执行 Exchange 2010 操作。我可以建立连接,如下所示。我的问题:如何在不明确指定凭据的情况下创建连接?不能通过当前的windows用户身份来获取吗?
SecureString password = new SecureString();
string str_password = "pass";
string username = "userr";
string liveIdconnectionUri = "http://exchange.cccc.com /Powershell?serializationLevel=Full";
foreach (char x in str_password)
{
password.AppendChar(x);
}
PSCredential credential = new PSCredential(username, password);
// Set the connection Info
WSManConnectionInfo connectionInfo = new WSManConnectionInfo((new Uri(liveIdconnectionUri)), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential);
connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
最佳答案
尝试[System.Net.NetworkCredential]::DefaultCredentials
。来自文档:
DefaultCredentials represents the system credentials for the current security context in which the application is running. For a client-side application, these are usually the Windows credentials (user name, password, and domain) of the user running the application.
此函数来自PoshCode.org script显示如何从 net cred 转换为 ps cred:
Function ConvertTo-PSCredential {
#.Synopsis
# Helper function which converts a NetworkCredential to a PSCredential
Param([System.Net.NetworkCredential]$Credential)
New-Object System.Management.Automation.PSCredential `
"$($Credential.UserName)@$($Credential.Domain)", `
(ConvertTo-SecureString $Credential.Password -AsPlainText -Force)
}
请注意,原始 PoshCode 函数中有一些无关的、未使用的脚本,我已将其删除。
关于c# - Exchange 2010 + Powershell 和 C# 从当前用户获取 PSCredential 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4955689/