簡體   English   中英

如何從Powershell腳本獲取值到C#變量中?

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

我有.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“” [-調試]

直接使用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