将Powershell变量传递到PS脚本中的C#代码 [英] passing powershell variables to C# code within PS script
问题描述
我读了很多有关将var从C#传递到powershell脚本的信息,但是我对另一种方式很感兴趣.
I read a lot about passing vars from C# to powershell script but i am interesten in the other way around.
在这里,我有以下代码在Powershell脚本中创建Type:
here I have this code to create a Type in my powershell script:
Add-Type @'
public class Node
{
public string Type;
public string VM_Name;
public string VM_IP;
public string Hostname;
}
'@
$vm1 = New-Object Node
$vm2 = New-Object Node
$vm3 = New-Object Node
$vm4 = New-Object Node
此代码后,我有C#代码:
After this code I have C# code:
$sourceCode = @'
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void InitializeComponent()
{
}
}
'@
如何使用上面的C#代码访问$ vm1,2,3,4?
How I might be able to access $vm1,2,3,4 in the C# code above ?
推荐答案
您可以通过C#类中的一种将变量作为参数接受的方法,将变量传递给类型,例如:
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)
我推荐这种方法.
另一种选择(较重且未经测试)是尝试从C#代码访问当前运行空间,例如:
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];
...
我还没有从C#代码中尝试过此操作(仅在PowerShell中),所以我不是100%确信它会工作.
I haven't tried this from C# code (only from within PowerShell) so I'm not 100% sure it will work.
这篇关于将Powershell变量传递到PS脚本中的C#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!