我想通过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命令
猜你喜欢
- UGUI轮播图组件实现方法详解 2023-01-16
- 用Linq从一个集合选取几列得到一个新的集合(可改列名) 2023-02-03
- C#中Socket与Unity相结合示例代码 2022-11-15
- Unity3D UGUI实现翻书特效 2023-02-03
- 详解C#多线程编程之进程与线程 2023-03-03
- C#中的数组用法详解 2023-05-30
- Unity 从Resources中动态加载Sprite图片的操作 2023-04-10
- C#特性(Attribute) 2023-05-25
- C#中泛型举例List<T>与DataTable相互转换 2023-06-05
- C# Linq延迟查询的执行实例代码 2023-04-14