tags:

views:

838

answers:

2

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

Hans-Arne sandem

A: 

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.

tomasr
Thank tou for the answer!I hope i don't have to write ancustom host. I only need to prompt for credentials and get a PSCredential object back. The credentials should not be verified because I need to pass on username password for a remote computer i a workgroup.Is there a way to get hold of the default PShost object of an Runspace? and then call the PromtForCredential like described here http://msdn.microsoft.com/en-us/library/system.management.automation.pscredential%28VS.85%29.aspx
Hans-Arne Sandem
I'm not sure I understand what you're doing, then. In what context are you trying to get these credentials? In a PowerShell Script? If so, then calling Get-Credential is really the way to go, and since this is a very thin wrapper on top of PSHostUserInterface.PromptForCredential(), if Get-Credential isn't working, the other won't, either.Where is your script running?
tomasr
If you're writing a C# app that uses powershell cmdlets, you are basically writing a host, and will have to implement this yourself. If you're writing a cmdlet ... you should just add a parameter which accepts the credentials from the user, and not try getting them yourself at all.
Jaykul
+3  A: 

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.

Keith Hill
Remember that you need to inherit from PSCmdlet instead of Cmdlet for this to work.
Skrymsli