Powershell:如何从 C# 代码中获取凭据? [英] Powershell: How do i get credentials from C# code?
问题描述
我曾尝试调用Get-Credential"CMDlet,但没有走运.阅读 Powershell SDK 我发现抽象方法PSHostUserInterface.PromptForCredential Method (String, String, String, String)".有实现这个方法的对象吗?
I have tried to call "Get-Credential" CMDlet without luck. Reading Powershell SDK i find the abstract method "PSHostUserInterface.PromptForCredential Method (String, String, String, String) ". is there any object whitch implement this method?
还有其他解决方案吗?
问候
推荐答案
通过当前 Host 的 UI 对象来提示用户输入凭据,如下所示:
Go through the current Host's UI object to prompt the user for a credential like so:
PSCredential cred = this.Host.UI.PromptForCredential("Enter username/password",
"", "", "");
但是,如果您正在创建一个 cmdlet 并走这条路线而不是创建凭据参数,那么用户将无法以自动方式(即通过凭据参数的参数)提供凭据.
However, if you are creating a cmdlet and go this route rather than creating a Credential parameter then the user will not be able to supply credentials in an automated fashion (ie through an argument to the Credential parameter).
顺便说一句,如果您的程序知道凭据并且您不想提示最终用户,那么您可以直接创建一个新的 PSCredential,例如:
BTW if your program knows the credentials and you don't want to prompt the end user then you can create a new PSCredential directly e.g.:
var password = new SecureString();
Array.ForEach("opensesame".ToCharArray(), password.AppendChar);
var cred = new PSCredential("john", password);
但是我不会在 EXE 中硬编码密码.我会使用 DPAPI 或类似的东西.
However I wouldn't hardcode the password in the EXE. I would use DPAPI or something like that.
这篇关于Powershell:如何从 C# 代码中获取凭据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!