我想通过C#代码添加Powershell命令或脚本(正确吗?)变量声明,并将默认值存储在C#变量中.例如,在Powershell中,我输入以下行$user = Admin我想在C#代码中添加此行.powershell.AddScript(String.Format($user = \{0...

我想通过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.
解决方法:
根据这篇文章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();
另请参见此处关于Stackoverflow的Run Powershell-Script from C# Application问题.
织梦狗教程
本文标题为:通过C#代码执行Powershell命令


基础教程推荐
猜你喜欢
- c# – 等待HttpWebRequest.BeginGetResponse在Windows Phone 7中完成 2023-09-19
- c# – 使用ORM创建数据库 2023-11-10
- C# winform自定义翻页控件详解 2022-11-14
- Audio Source组件及相关API 2022-11-27
- 一篇文章看懂C#中的协变、逆变 2023-01-28
- 基于C#实现的多边形冲突检测实例 2023-04-21
- Unity3D实现射线使物体移动 2023-02-03
- C#多线程系列之任务基础(一) 2023-05-21
- Unity实现场景加载功能 2023-05-05
- C#使用base64对字符串进行编码和解码的测试 2023-01-11