0

I am trying to run sample powershell script from .net core application. Basically i need to give parameters to script and utilized parameters inside script,but doesn't seem working.

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());
    }
  }
}

Expected Output:

sid

Any help. Thanks in advance.

mklement0
  • 382,024
  • 64
  • 607
  • 775
cj devin
  • 1,045
  • 3
  • 13
  • 48
  • 1
    To add to Daniel's helpful answer: [`Write-Host` is typically the wrong tool to use](http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/), unless the intent is to write _to the display only_, bypassing the success output stream and with it the ability to send output to other commands, capture it in a variable, or redirect it to a file. To output a value, use it _by itself_; e.g., `$value` instead of `Write-Host $value` (or use `Write-Output $value`, though that is rarely needed); see [this answer](https://stackoverflow.com/a/60534138/45375) – mklement0 Jul 16 '21 at 15:00

1 Answers1

1

You C# code looks okay. I believe the issue lies in your PowerShell script. Write-Host sends string values to the information stream which will not populate into pipelineObjects (however you will find this output in ps.Streams.Information). To write the $SubscriptionId to the pipeline and ultimately into your pipelineObjects collection just remove Write - Host (which has extra spaces in it anyways and would error).

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

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

  RunScript(scriptContent, scriptParameters);
}
Daniel
  • 4,792
  • 2
  • 7
  • 20