【问题标题】:.Net Core sample powershell script example that take parameters.Net Core 示例 powershell 脚本示例,带参数
【发布时间】: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-Host is typically the wrong tool to use,除非意图是仅写入显示,绕过成功输出流并具有发送输出的能力到其他命令,将其捕获在变量中,或将其重定向到文件。要输出一个值,请单独使用它;例如,$value 而不是 Write-Host $value(或使用 Write-Output $value,尽管很少需要);见this answer

标签: c# powershell .net-core


【解决方案1】:

您的 C# 代码看起来不错。我相信问题在于您的 PowerShell 脚本。 Write-Host 将字符串值发送到不会填充到pipelineObjects 中的信息流(但是您会在ps.Streams.Information 中找到此输出)。要将$SubscriptionId 写入管道并最终写入您的pipelineObjects 集合,只需删除Write - Host(其中有额外的空格并且会出错)。

static void Main() {
  string scriptContent = @"param($SubscriptionId) $SubscriptionId";

  Dictionary < string, object > scriptParameters = new Dictionary < string, object > ();
  scriptParameters.Add("SubscriptionId", "sid");

  RunScript(scriptContent, scriptParameters);
}

【讨论】:

    猜你喜欢
    • 2012-02-02
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2021-03-25
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多