Return powershell variable value to c# application

后端 未结 2 1028
庸人自扰
庸人自扰 2021-01-22 03:08

I am running powershell script from c#.

string scriptPath = \"/script/myscript.ps1\";
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pi         


        
相关标签:
2条回答
  • 2021-01-22 03:27
    string variable_to_return_from_ps_script = "test"; 
    
    // create Powershell runspace
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    
    //
    // here you write the code to invoke the PS script, pipeline, pass parameters etc...
    // just like the code you already have
    //
    
    // and here's how you retrieve a variable test from PS
    var out_var = runspace.SessionStateProxy.PSVariable.GetValue(variable_to_return_from_ps_script);
    Console.WriteLine("Variable ${0} value is: ", variable_to_return_from_ps_script);
    Console.WriteLine(out_var.ToString());
    
    0 讨论(0)
  • 2021-01-22 03:33

    I know I am late to this, but in your script, you need to add global: in front of the variable you want to return in the Powershell script, so for example:

    $global:test = 4
    

    in Powershell script. In C# after you open the runspace, invoke the policy changer, set up the pipline, you do

    var result = runspace.SessionStateProxy.PSVariable.GetValue("test");
    
    0 讨论(0)
提交回复
热议问题