如何从powershell脚本获取值到C#变量?
问题描述:
我有.ps1脚本应该返回当前用户(或管理员)的SID。但我不知道如何从脚本中获取这个值到我的C#代码中。请有人帮助我吗?如何从powershell脚本获取值到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]
答
直接使用,而不是推出powershell.exe
的API:
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
}
}
+0
非常棒!.... – user7968180
你打电话给ps1脚本怎么样?请显示代码。一种典型的方法是让脚本回显结果,如果脚本成功,调用程序将字符串解析为变量。请参阅[问]和[mcve]了解如何编辑您的问题。 –
我已更新我的问题,请看一下。 – user7968180
在*搜索框中输入以下内容:“C#PowerShell” - 我看到很多示例 –