Use 'Connect-AzAccount' command of PowerShell in C#

Juanjo 1 Reputation point
2021-07-14T13:54:10.53+00:00

I want to connect to Azure the same way I log in using Powershell commands. Since I have not found any API to do that with .NET, I though that a good dea would be to execute PS scripts with .NET.

I have already installed the Powershell for azure in my laptop

Install-Module -Name Az -AllowClobber

I also tried to use the 'Connect-AzAccount' command just with the Windows Powershell of my PC and it works fine.

So, I tried the following in Visual Studio:

using System.Management.Automation;

namespace AzureTestVM
{ 
    class Program
    {

        static void Main(string[] args)
        {
            PowerShell ps = PowerShell.Create().AddCommand("Connect-AzAccount");
            ps.Invoke();
        }
    }
}

The problem is that I get the following error:

Unhandled Exception: System.Management.Automation.CmdletInvocationException: Method 'get_SerializationSettings' on type' Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient 'of assembly' Microsoft.Azure.PowerShell.Clients.ResourceManager, Version = 1.0. 0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35 'does not have an implementation. ---> System.TypeLoadException: Method 'get_SerializationSettings' on type' Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient 'of assembly' Microsoft.Azure.PowerShell.Clients.ResourceManager, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35 'does not have an implementation.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,292 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,383 questions
{count} votes