【发布时间】:2021-09-24 23:56:11
【问题描述】:
我正在尝试从 .net 核心应用程序运行示例 powershell 脚本。 基本上我需要为脚本提供参数并在脚本中使用参数,但似乎不起作用。
static void Main() {
string scriptContent = @ "param($SubscriptionId)
Write-Host $SubscriptionId ";
Dictionary < string, object > scriptParameters = new Dictionary < string, object > ();
scriptParameters.Add("SubscriptionId", "sid");
RunScript(scriptContent, scriptParameters);
}
public async Task RunScript(string scriptContents, Dictionary < string, object > scriptParameters) {
// create a new hosted PowerShell instance using the default runspace.
// wrap in a using statement to ensure resources are cleaned up.
using(PowerShell ps = PowerShell.Create()) {
// specify the script code to run.
ps.AddScript(scriptContents);
// specify the parameters to pass into the script.
ps.AddParameters(scriptParameters);
// execute the script and await the result.
var pipelineObjects = await ps.InvokeAsync().ConfigureAwait(false);
// print the resulting pipeline objects to the console.
foreach(var item in pipelineObjects) {
Console.WriteLine(item.BaseObject.ToString());
}
}
}
预期输出:
sid
任何帮助。 提前致谢。
【问题讨论】:
-
添加到 Daniel 的有用答案:
Write-Hostis typically the wrong tool to use,除非意图是仅写入显示,绕过成功输出流并具有发送输出的能力到其他命令,将其捕获在变量中,或将其重定向到文件。要输出一个值,请单独使用它;例如,$value而不是Write-Host $value(或使用Write-Output $value,尽管很少需要);见this answer
标签: c# powershell .net-core