开发者

Exchange 2010 + Powershell and C# problems getting PSCredential from current user

I'd like to perform Exchange 2010 operations with the powershell via C#. I can establish the connection as shown below. My question: How can I create the connection without explicitly specifying the credentials? Can't I get it through the current windows user identity?

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;


Try [System.Net.NetworkCredential]::DefaultCredentials. From the docs:

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.

This function from a PoshCode.org script shows how to convert from a net cred to a 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)
}

Note that the original PoshCode function had some extraneous, unused script in it that I removed.


I don't know of a way to create a PSCredential object from a security token. I think the general workflow is to prompt the user for credentials in these situations to avoid holes related to security elevation.

You should probably prompt the user for their credentials using the PSHostUserInterface.PromptForCredentials method.

There are also some examples of caching credentials: "PowerShell Script: Export-PSCredential and Import-PSCredential". Use at your own risk

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜