0

enter image description hereI am facing an issue while connecting to Azure through the power shell. could you please help me to resolve the issue? code is below, please tell me where I am making a mistake.

we are using .net 7.0 to execute power shell and connect to azure

 using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
using System.Management.Automation;
using System.Windows;
using Microsoft.PowerShell;

namespace ConsoleApppowershell
{
    internal class ConsoleApppowershell
    {
        private static async Task Main(string[] args)
        {
            string _state = "Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine Get-ExecutionPolicy";
            InitialSessionState iss = InitialSessionState.CreateDefault();
            //iss.ImportPSModule(new string[] { "AzureAD" });
            iss.ExecutionPolicy = ExecutionPolicy.Unrestricted;
            iss.ExecutionPolicy = (ExecutionPolicy)ExecutionPolicyScope.CurrentUser;
            iss.ThrowOnRunspaceOpenError = false;
            Runspace runspace = RunspaceFactory.CreateRunspace(iss);
            PowerShell ps = PowerShell.Create(runspace);
            runspace.Open();
            ps.AddScript(_state).Invoke();
            //await ps.AddScript("Get-ExecutionPolicy").InvokeAsync();
            await ps.AddParameter("-ExecutionPolicy", "Unrestricted").InvokeAsync();
            //await ps.AddScript("Install-Module -Name AzureAD -Force").InvokeAsync();
            await ps.AddScript("Import-Module -Name AzureAD -UseWindowsPowerShell").InvokeAsync();
            //PowerShell ps = PowerShell.Create(runspace);
            ps.AddCommand("Connect-AzureAD");
            ps.AddParameters(new Dictionary<string,[![enter image description here][1]][1]object>
            {

                ["ApplicationId "] = " ",

                ["CertificateThumbprint"] = " ",

                ["TenantId"] = " "

            });
            Collection<PSObject> connectionResult = ps.Invoke();
            ps.Commands.Clear();
            ps.AddCommand("Get-AzureADGroup");
            ps.AddParameter("Filter", "DisplayName eq 'O365_ENTERPRISE_E5_DEVELOPER'");
            Collection<PSObject> results = ps.Invoke();
            if (!ps.HadErrors)
            {
                foreach (PSObject result in results)
                {
                    Console.WriteLine(result.ToString());
                }
            }
            else
            {
                foreach (ErrorRecord error in ps.Streams.Error)
                {
                    Console.WriteLine(error.ToString());
                }
          }
        }
    }
}
5
  • The path of the cmdlets are not found (or cmdlet is not installed). Try using fullpath of the cmdlets : C:\Windows\System32\WindowsPowerShell\v1.0\Connect-AzureAd Commented Jan 23, 2024 at 13:04
  • Hi Jdweng , Thank you for your replay but i did not understand , could you please explain in details Commented Jan 23, 2024 at 13:45
  • Do the commands work if you run them in an interactive PowerShell session? It might be easier to try to eliminate C# as a moving part first if you get the same error interactively... Commented Jan 23, 2024 at 15:26
  • PS cmdlets are normally installed in the folder shown in my 1st comment. The cmdlet may be in other locations on your machine. Try searching for the cmdlet on you machine to find full path. Commented Jan 23, 2024 at 16:05
  • why not use the c# Graph SDK then you don't need powershell at all.. you don't even need the SDK either, can make a call to the groups API using the HttpClient class Commented Jan 24, 2024 at 5:04

1 Answer 1

0

How to call PowerShell script to connect azure

I do agree with @jdweng and Alternatively, below is the code how I connect PowerShell with .Net7 and use the azure PowerShell commands with it and i followed SO-thread:

using System.Diagnostics;
using System.Text;
public class RithPowerShellCommandRunner
{
    public static string ExceutePowershellCommand(string command)
    {
        var rith_procStartInfo = new ProcessStartInfo
        {
            FileName = "powershell.exe",
            Arguments = $"-Command \"{command}\"",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        using (var rith_pro = new Process { StartInfo = rith_procStartInfo })
        {
            rith_pro.Start();

            string rith_out = rith_pro.StandardOutput.ReadToEnd();
            string error = rith_pro.StandardError.ReadToEnd();

            rith_pro.WaitForExit();

            if (rith_pro.ExitCode == 0)
            {
                return rith_out;
            }
            else
            {
                throw new InvalidOperationException($"Hello Rithwik Bojja, execution of command failed and the Error: {error}");
            }
        }
    }

    public static void Main()
    {
        StringBuilder rith = new StringBuilder();
        rith.AppendLine("Import-Module -Name AzureAD");
        rith.AppendLine("Connect-AzureAD");
        rith.AppendLine("Get-AzureADUser -SearchString 'Test 12'");
        string rithwik_output = ExceutePowershellCommand(rith.ToString());
        Console.WriteLine(rithwik_output);
    }
}

csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Cake.Powershell" Version="3.0.0" />
    <PackageReference Include="System.Management.Automation" Version="7.3.11" />
  </ItemGroup>

</Project>

Output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.