0

I am trying to build a C# console app that executes a series of PowerShell commands that run against an Azure Subscription.

var line1 = "$cred = Get-Credential"
var line2 = "Add-AzureAccount -Credential $cred"
var psi = PowerShell.Create()
psi.AddCommand(line1);
psi.AddCommand(line2);
var output = psi.Invoke();

I thought it would present an interactive login box, and then continue to run. Instead, this is thrown:

An unhandled exception of type 'System.Management.Automation.CommandNotFoundException' occurred in System.Management.Automation.dll Additional information: The term '$cred = Get-Credential' is not recognized as the name of a cmdlet, function, script file, or operabl...

If I start PowerShell from CMD, and type

$cred = Get-Credential

I get presented with the default interactive logon box, user can enter credentials and they are captured to $cred and I can move on.

What is the right set of commands to make this work in C#?

Thanks.

Snowy
  • 5,942
  • 19
  • 65
  • 119
  • There is not command with such weird name `$cred = Get-Credential` or `Add-AzureAccount -Credential $cred` in PowerShell by default. Also, `Get-Credential` does not provide interactive login box. Interactive login box provided by `$Host.UI.PromptForCredential`. So, you need to supply `PSHost` instance which support this method. – user4003407 Jul 08 '16 at 05:06
  • @PetSerAl - I do not understand how to present user with the familiar interactive default logon box when running Posh from C#. Ideally I want to take Posh that works and run it within .NET code, how to do that? – Snowy Jul 08 '16 at 17:55

1 Answers1

0

It's not a small task, but you can create ui in powershell using Wpf. Launched from a. NET console app you can create a powershell runspace, create your login prompt ui and go from there. We did this, but had a really specific usecase - for most scenarios you'd not normally mix the two up as you're suggesting. https://foxdeploy.com/2015/04/10/part-i-creating-powershell-guis-in-minutes-using-visual-studio-a-new-hope/

GordonBy
  • 3,099
  • 6
  • 31
  • 53