无法在.NET 8中导入ActiveDirectory模块,可在Powershell中使用

问题描述 投票:0回答:1

我尝试从 .NET 8 运行 Powershell 命令,但遇到错误:

无法加载文件或程序集“Microsoft.ActiveDirectory.Management、Culture=neutral、PublicKeyToken=null”。系统找不到指定的文件。

该项目安装了 Nuget 包 Microsoft.Powershell.SDK。我还通过 Windows 11 上的“添加功能”安装了 PowerShell Active Directory 模块。

我创建了一个控制台应用程序只是为了尝试使用以下代码打开运行空间:

using System.Management.Automation.Runspaces;
...
var initial = InitialSessionState.CreateDefault();
initial.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;

initial.ImportPSModule(["ActiveDirectory"]);
using var runspace = RunspaceFactory.CreateRunspace(initial);

try
{
    runspace.Open();
}
catch(Exception ex)
{
    Console.WriteLine(ex.ToString());
}

我尝试安装每个 RSAT 软件包,重新启动电脑几次,检查我是否直接使用 SDK 而不是 System.Management.Automation Nuget。我的 system32/WindowsPowershell/v1.0/Modules 中安装了一个模块 ActiveDirectory,我的 WinSys 文件夹中有 .dll 文件。我从 Powershell 运行任何我想要的东西都没有问题,但 .NET 无法识别它的存在。

c# .net azure powershell active-directory
1个回答
0
投票

在 .net 8 中运行 AD Powershell 命令?

我遵循了SO-thread的回答,下面是对我有用的代码:

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

        using (var rithwik_pro = new Process { StartInfo = rithwik_procStartInfo })
        {
            rithwik_pro.Start();

            string rith_out1 = rithwik_pro.StandardOutput.ReadToEnd();
            string error = rithwik_pro.StandardError.ReadToEnd();

            rithwik_pro.WaitForExit();

            if (rithwik_pro.ExitCode == 0)
            {
                return rith_out1;
            }
            else
            {
                throw new InvalidOperationException($"Hello Rithwik Bojja there is an expection, execution of command failed and the Error: {error}");
            }
        }
    }

    public static void Main()
    {
        StringBuilder rithwik = new StringBuilder();
        rithwik.AppendLine("Import-Module -Name AzureAD");
        rithwik.AppendLine("Connect-AzureAD");
        rithwik.AppendLine("Get-AzureADUser -SearchString 'Quality System'");
        string rith_output = TestRithwik(rithwik.ToString());
        Console.WriteLine(rith_output);
    }
}

Output:

enter image description here

csproj:

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

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

  <ItemGroup>
    <PackageReference Include="System.Management.Automation" Version="7.4.1" />
  </ItemGroup>

</Project>
© www.soinside.com 2019 - 2024. All rights reserved.