【发布时间】:2019-05-22 22:51:06
【问题描述】:
当我尝试在我的 c# 应用程序中使用 PowerShell cmdlet“Get-LocalGroup”时,它不会在我的控制台上打印出此 cmdlet 的任何输出。
我已经包含了 Management.Automation NuGet。 构建过程没有问题。 我还尝试在调试和发布模式下以管理员权限启动构建的 .exe。
using System.Collections.ObjectModel;
using System.Management.Automation;
namespace RunPowershell
{
class Program
{
static void Main(string[] args)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("Get-LocalGroup");
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
// loop through each output object item
foreach (PSObject outputItem in PSOutput)
{
if (outputItem != null)
{
System.Console.WriteLine("-"+outputItem.BaseObject);
}
}
System.Console.WriteLine("Hit any key to exit.");
System.Console.ReadKey();
}
}
}
}
我在调试窗口中看不到明显错误,但也没有“Get-LocalGroup”的输出。
【问题讨论】:
-
我不喜欢 C#,但我认为你需要做
using (PowerShell PowerShellInstance = PowerShell.Create("Get-LocalGroup"))并删除行PowerShellInstance.AddScript("Get-LocalGroup");。另外,根据您想要的输出,我会尝试System.Console.WriteLine("-" + outputItem.Name);
标签: c# powershell