【发布时间】:2020-12-16 04:10:45
【问题描述】:
我正在尝试从我的 C# 控制台应用程序执行 .ps1 文件。使用下面提供的代码,您可以看到我想要做什么:
public static void execitePs(string originalString)
{
using (PowerShell ps = PowerShell.Create())
{
// specify the script code to run.
ps.AddScript(@"C:\PnP\test_script_json.ps1");
// specify the parameters to pass into the script.
ps.AddParameter("originalString", originalString);
// execute the script and await the result.
var pipelineObjects = ps.Invoke();
// print the resulting pipeline objects to the console.
foreach (dynamic item in pipelineObjects)
{
Console.WriteLine(item);
}
}
}
基本上,我正在尝试为 AddScript 方法提供文件路径,如 Microsoft 示例中所述。这应该调用脚本文件并执行它。以下是脚本文件内容:
param ($originalString)
$JSONString = @"
$originalString
"@
Write-Output HEREEEEEEEE
$cusomObject = ConvertFrom-Json $JSONString
Write-Host $cusomObject.Name
整个过程基本上就是取一些JSON作为参数,打印属性name。
即使 JSON 缺少属性,它也应该将 HEREEEEEEEE 字符串打印到控制台。
结果我没有得到任何输出,因为调用脚本后@987654327@ 集合为空。
此外,我已经设法使用以下方法成功执行它:
Process.Start(@"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe", @"-File ""C:\PnP\test_script_json.ps1"" """ + originalString + "");
但使用它不是那么灵活。
有什么想法可以使用PowerShell 对象来做同样的事情吗?
感谢任何帮助/想法!
最好的问候,迪米塔尔
【问题讨论】:
-
我在启动 Powershell 脚本以使用 C# 从 JSON 对象获取值时遇到了一些麻烦。是否有更深层次的需要额外的复杂性?
-
我正在执行自动化流程来部署 SharePoint 网站。后端 .NET 但自动化过程应使用 PnP Powershell(特殊要求)。因此,在我看来,将复杂对象从 C# 传递到 Powershell 的最简单方法是 JSON。这就是为什么需要这样的过程。
标签: c# powershell .net-core