You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过C#调用PowerShell执行Get-LocalGroupMember时PrincipalSource属性为空

解决C#调用PowerShell获取Get-LocalGroupMember时PrincipalSource为空的问题

在Windows 10(PowerShell 5.1、.NET Framework 4.8)环境下,通过C#调用PowerShell执行Get-LocalGroupMember -Group Administrators时,可正常获取ObjectClass、Name等属性,但PrincipalSource属性始终为空。

问题原因

这是因为PowerShell SDK默认不会自动加载Microsoft.PowerShell.LocalAccounts模块的完整类型扩展。PrincipalSource属于动态添加的属性,依赖模块的类型扩展定义才能被正确填充;而在交互式PowerShell会话中,模块会自动加载并应用这些扩展,因此能正常显示该属性值。

解决方案

方案1:显式导入LocalAccounts模块

在执行Get-LocalGroupMember命令前,先显式导入Microsoft.PowerShell.LocalAccounts模块,确保类型扩展被加载:

PowerShell powershell = PowerShell.Create();

// 导入LocalAccounts模块
powershell.AddCommand("Import-Module").AddParameter("Name", "Microsoft.PowerShell.LocalAccounts");
powershell.Invoke();
powershell.Commands.Clear();

// 执行目标命令
powershell.AddCommand("Get-LocalGroupMember").AddParameter("Group", "Administrators");
Collection<PSObject> results = powershell.Invoke();

// 遍历结果并输出
foreach (PSObject obj in results)
{
    var objectClass = obj.Members["ObjectClass"].Value;
    var name = obj.Members["Name"].Value;
    var principalSource = obj.Properties["PrincipalSource"]?.Value ?? "未获取到";
    
    Console.WriteLine("{0,-20}{1,-30}{2}", objectClass, name, principalSource);
}
Console.WriteLine("End");

powershell.Dispose();

方案2:使用Select-Object强制保留属性

通过管道调用Select-Object并指定包含PrincipalSource,强制PowerShell返回该属性的值:

PowerShell powershell = PowerShell.Create();

powershell.AddCommand("Get-LocalGroupMember")
          .AddParameter("Group", "Administrators")
          .AddCommand("Select-Object")
          .AddParameter("Property", new string[] { "ObjectClass", "Name", "PrincipalSource" });

Collection<PSObject> results = powershell.Invoke();

foreach (PSObject obj in results)
{
    Console.WriteLine("{0,-20}{1,-30}{2}",
        obj.Properties["ObjectClass"].Value,
        obj.Properties["Name"].Value,
        obj.Properties["PrincipalSource"]?.Value ?? "未获取到");
}
Console.WriteLine("End");

powershell.Dispose();

针对脚本路径调用的适配

如果使用方式一(通过脚本路径调用),只需在脚本开头添加模块导入语句即可:

# 脚本开头添加
Import-Module Microsoft.PowerShell.LocalAccounts
Get-LocalGroupMember -Group Administrators

内容的提问来源于stack exchange,提问作者Mr. Pramod Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 13:00:26