Powershell: How do i get credentials from C# code?
I have tried to call "Get-Credential" CMDlet without luck. Reading Powershell SDK i find the abstract method "PSHostUserInterface.PromptForCredential Met开发者_高级运维hod (String, String, String, String) ". is there any object whitch implement this method?
Any other solution?
Regards
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",
"", "", "");
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).
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);
However I wouldn't hardcode the password in the EXE. I would use DPAPI or something like that.
Are you writing a custom PSHost? If so, then your custom host would be required to provide your own implementation of PSHostUserInterface and then implement PromptForCredential() in it.
If you need to implement this yourself, and want to use the standard windows credentials dialog that PowerShell uses by default, then you could use the CredUIPromptForCredentials() api. There's some code on how to call it from .NET here and here.
精彩评论