c# - 将 powershell 变量值返回给 c# 应用程序

标签 c# powershell

我正在从 C# 运行 powershell 脚本。

string scriptPath = "/script/myscript.ps1";
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptPath);
Collection<PSObject> results = pipeline.Invoke(); 

例如,如果我的 myscript.ps1 文件如下;

$test=4
$test++
$test

执行脚本后如何获取变量test值。我需要将该值添加到我的 C# 程序中。

最佳答案

我知道我迟到了,但是在您的脚本中,您需要在 Powershell 脚本中要返回的变量前面添加 global:,例如:

$global:test = 4

在 Powershell 脚本中。在 C# 中,打开运行空间后,调用策略更改器,设置 pipline,您可以这样做

var result = runspace.SessionStateProxy.PSVariable.GetValue("test");

关于c# - 将 powershell 变量值返回给 c# 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17467629/

相关文章:

powershell - 使用 foreach 更改数组中的值

c# - Android和iOS的跨平台网络状态检测——如果不是: how to implement on Android?

c# - xtraGrid gridControl 中的自定义 summerType

c# - SqlDataReader "Enumeration yielded no results"

c# - 在 C# 中需要有关正则表达式和模式匹配的帮助吗?

c# 将对象添加到列表框并在其中显示对象字符串

powershell - 使用Powershell编辑文本文件中的特定数据列

powershell - 复制项目缓慢 - 过滤和复制 5500 个文件需要 40 分钟?

mysql - PowerShell:ODBC DSN 连接中的多个查询

powershell - 如何导入CSV文件中每行的前两个值电源外壳