简体   繁体   中英

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 Method (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 eg:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM