Powershell: How to get credentials from C # code?

I have tried calling CMDlet Get-Credential with no luck. Reading Powershell SDK I find an abstract method "PSHostUserInterface.PromptForCredential Method (String, String, String, String)". is there any whitch object to implement this method?

Any other solution?

Hello

+2


source to share


2 answers


Step through the current host UI object to prompt the user for these credentials:

PSCredential cred = this.Host.UI.PromptForCredential("Enter username/password",
                                                     "", "", "");

      

However, if you create a cmdlet and go to that route instead of creating a Credential parameter, the user will not be able to automatically provide credentials (that is, via the Credential parameter argument).



By the way, if your program knows the credentials and you don't want to prompt the end user, then you can create a new PSCredential directly, like this:

var password = new SecureString();
Array.ForEach("opensesame".ToCharArray(), password.AppendChar);
var cred = new PSCredential("john", password);

      

However, I would not hardcode the password in the EXE. I would use DPAPI or something.

+4


source


Are you writing a custom PSHost? If so, then your custom host will need to provide your own PSHostUserInterface implementation and then implement PromptForCredential () in it.



If you need to implement this yourself and want to use the standard Windows credentials dialog which PowerShell uses by default, you can use the CredUIPromptForCredentials () api. There's some code on how to call it from .NET here and here .

+1


source







All Articles