PowerShell AddCommand called from C# Exception

375 Views Asked by At

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.

1

There are 1 best solutions below

0
On

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/