C#如何将CredentialCache.DefaultCredentials转换为PSCredential?

时间:2012-07-24 11:56:26

标签: c# powershell credentials

我正在编写一个c#程序,它将使用当前用户的凭据来运行脚本。

如何在访问网络服务中将CredentialCache.DefaultCredentials对象转换为PSCredential对象?

或者其他更好的方法来创建PSCredential而不存储用户名/密码?

1 个答案:

答案 0 :(得分:0)

此处不保证,但您至少可以尝试类似下面的伪代码

// DefaultCredentials returns an ICredentials reference
// which can then be used to call GetCredentials, 
// and *that* returns a NetworkCredential.
NetworkCredential netCredential = CredentialCache.DefaultCredentials.GetCredentials(..);

// Now, with a NetworkCredential that *might* have a SecurePassword, you 
// could see if that would work to create a PSCredential. I haven't tested this,
// and honestly I'm a bit dubious of the prospects, but its at least a thought.
// There may be some translation necessary to even make that SecurePassword work,
// assuming it is even available in your context, to something the PSCredential
// can use. 

PSCredential psCredential = new PSCredential(netCredential.UserName, 
                                             netCredential.SecurePassword);

如上所述,这是未经测试的伪代码,但希望它能为您提供正确的方向。祝你好运。

相关问题