简体   繁体   English

如何从Powershell脚本获取值到C#变量中?

[英]How to get value from powershell script into C# variable?

I have .ps1 script which should return me SID of current user (or administrator). 我有.ps1脚本,该脚本应返回当前用户(或管理员)的SID。 But i have no idea how can i get this value from that script into my C# code. 但是我不知道如何从脚本中获取此值到C#代码中。 Can somebody help me, please? 有人可以帮我吗?

Currently i am calling one script in this way: 目前,我以这种方式调用一个脚本:

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""";

And i need to get SID of user from another .ps1 script and then use it in this cmd command: 我需要从另一个.ps1脚本获取用户的SID,然后在此cmd命令中使用它:

HotelMode.ps1 -UserSid "" [-debug] HotelMode.ps1 -UserSid“” [-调试]

Use the System.Management.Automation API directly instead of launching powershell.exe : 直接使用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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM