c# - 从 C# 项目执行 .ps1 文件作为参数
问题描述
我正在尝试.ps1
从我的 C# 控制台应用程序执行文件。使用下面提供的代码,您可以看到我正在尝试做什么:
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
字符串打印到控制台。
结果我没有得到任何输出,因为pipelineObjects
调用脚本后集合为空。
此外,我设法使用以下方法成功执行它:
Process.Start(@"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe", @"-File ""C:\PnP\test_script_json.ps1"" """ + originalString + "");
但使用它不是那么灵活。
有什么想法可以使用该PowerShell
对象做同样的事情吗?
任何帮助/想法表示赞赏!
最好的问候, 迪米塔尔
解决方案
我使用这个辅助方法。
private Process CreateAndStartProcess(string fileName, string arguments)
{
var startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Normal,
FileName = fileName,
WorkingDirectory = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0",
Arguments = arguments,
RedirectStandardOutput = true,
CreateNoWindow = false,
RedirectStandardError = true,
UseShellExecute = true
};
var process = new Process
{
StartInfo = startInfo
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
return process;
}
您可以通过启动它
var arguments = @"-File C:\PnP\test_script_json.ps1" + originalString;
var process = CreateAndStartProcess("powershell.exe", arguments);
推荐阅读
- php - 在哪里可以找到通过 TCP 接收的 GPS 数据?
- javascript - ajax循环settimeout,仅在前一个请求完成后才新请求
- javascript - 使用 new 关键字在构造函数中创建类的实例是不好的做法吗?
- c# - MVVMCross 如何实现 ContentDialog
- c# - 在 asp.net MVC 中处理 localhost 时,smpt 未在已发布时发送电子邮件
- wcf - SOAP Onvif 对 WCF 客户端没有响应
- swift - 展开“字符串?” 快速变量?
- php - 来自五个 Mysql 表的每个国家、州、城市和地区的销售额总和
- ios - 如何以编程方式创建带有动态选项卡的选项卡栏?底部黑屏问题
- android - 电报发送未保存的联系人