如何从powershell脚本获取C#变量的值?

时间:2017-06-10 19:13:25

标签: c# powershell

我有.ps1脚本,它应该返回当前用户(或管理员)的SID。但我不知道如何从该脚本中获取此值到我的C#代码中。拜托,有人可以帮助我吗?

目前我正以这种方式调用一个脚本:

ProcessStartInfo newProcessInfo = new ProcessStartInfo();
newProcessInfo.FileName = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe";
newProcessInfo.Verb = "runas";
newProcessInfo.Arguments = @"sfc /scannow";
Process.Start(newProcessInfo);

newProcessInfo.Arguments = @"-Command ""sfc /scannow""";
newProcessInfo.Arguments = @"–ExecutionPolicy Bypass -File ""c:\\Users\\HP\\Desktop\\HotelMode-PB\\HotelMode.ps1""";

我需要从另一个.ps1脚本获取用户的SID,然后在此cmd命令中使用它:

  

HotelMode.ps1 -UserSid“”[-debug]

1 个答案:

答案 0 :(得分:0)

直接使用System.Management.Automation API,而不是启动powershell.exe

using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
// ...
using(PowerShell ps = PowerShell.Create())
{
    ps.AddCommand("Set-ExecutionPolicy")
      .AddParameter("ExecutionPolicy","Bypass")
      .AddParameter("Scope","Process")
      .AddParameter("Force");

    ps.AddScript(@"C:\Users\HP\Desktop\HotelMode-PB\HotelMode.ps1");

    Collection<PSObject> result = ps.Invoke();
    foreach(var outputObject in result)
    {
        // outputObject contains the result of the powershell script
    }
}