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.

1
  • 1
    To add to Daniel's helpful answer: Write-Host is typically the wrong tool to use, 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 Commented Jul 16, 2021 at 15:00

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.