passing powershell variables to C# code within PS script

前端 未结 1 1366
一向
一向 2021-01-19 07:15

I read a lot about passing vars from C# to powershell script but i am interesten in the other way around.

here I have this code to create a Type in my powershell scr

相关标签:
1条回答
  • 2021-01-19 07:29

    You could either pass the variables into the type via a method in your C# class that would accept the variables as parameters e.g.:

    $form = new-object Form1
    $form.SetVariables($vm1, $vm2, $vm3, $vm4)
    

    I recommend that approach.

    Another option (heavier weight and not tested) is to try accessing the current runspace from the C# code e.g.:

    var defRunspace = System.Management.Automation.Runspaces.Runspace.DefaultRunspace;
    var pipeline = defRunspace.CreateNestedPipeline();
    pipeline.Commands.AddScript("$vm1,$vm2,$vm3,$vm4");
    var results = pipeline.Invoke();
    var vm1 = results[0];
    var vm2 = results[1];
    ...
    

    I haven't tried this from C# code (only from within PowerShell) so I'm not 100% sure it will work.

    0 讨论(0)
提交回复
热议问题