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.
Write-Hostis 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.,$valueinstead ofWrite-Host $value(or useWrite-Output $value, though that is rarely needed); see this answer