通过 C# 代码执行 Powershell 命令

Posted

技术标签:

【中文标题】通过 C# 代码执行 Powershell 命令【英文标题】:Powershell command through C# code 【发布时间】:2013-05-06 11:51:11 【问题描述】:

我想通过 C# 代码添加 Powershell 命令或脚本(什么是正确的?)变量声明,默认值存储在 C# 变量中。 例如,在 Powershell 中,我输入以下行

 $user = 'Admin'

我想在 C# 代码中添加这一行。

powershell.AddScript(String.Format("$user = \"0\"", userName));

powershell.AddCommand(String.Format("$user = \"0\"", userName));

我尝试使用 AddCommand() 但它会引发异常。我用的是 PS 2.0。

【问题讨论】:

你不应该改用AddScript方法吗? 【参考方案1】:

根据这篇文章How to run PowerShell scripts from C#,你需要这样的东西:

// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(String.Format("$user = \"0\"", userName));
pipeline.Commands.AddScript("#your main script");

// execute the script
Collection<psobject> results = pipeline.Invoke();
// close the runspace
runspace.Close();

另请参阅 *** 上的 Run Powershell-Script from C# Application 问题。

【讨论】:

以上是关于通过 C# 代码执行 Powershell 命令的主要内容,如果未能解决你的问题,请参考以下文章

运行 powershell 命令以在 c# 上按进程获取 GPU 使用情况

PowerShell命令与脚本(10)——脚本

C#通过代码调用PowerShell

无法从 C# 调用 Powershell 函数

c# - 如何在运行时从模块代码中获取 PowerShell 模块版本

C# 中未获取 Powershell 结果集