C#powershell脚本
我知道如何执行单个powershell命令并使用C#代码查看其结果。但我想知道如何执行一组相关命令,如下所示,并获得输出:C#powershell脚本,c#,powershell-2.0,C#,Powershell 2.0,我知道如何执行单个powershell命令并使用C#代码查看其结果。但我想知道如何执行一组相关命令,如下所示,并获得输出: $x = some_commandlet $x.isPaused() 简单地说,我想访问$x.isPaused()的返回值 如何将此功能添加到我的C#应用程序中?对于此类命令,最好创建一个称为管道的东西,并将脚本提供给它。我发现了一个很好的例子。您可以进一步了解此代码和此类项目 私有字符串运行脚本(字符串脚本文本) { //创建Powershell运行空间 Runspac
$x = some_commandlet
$x.isPaused()
简单地说,我想访问$x.isPaused()
的返回值
如何将此功能添加到我的C#应用程序中?对于此类命令,最好创建一个称为管道的东西,并将脚本提供给它。我发现了一个很好的例子。您可以进一步了解此代码和此类项目
私有字符串运行脚本(字符串脚本文本)
{
//创建Powershell运行空间
Runspace Runspace=RunspaceFactory.CreateRunspace();
//打开它
Open();
//创建一个管道并向其提供脚本文本
Pipeline Pipeline=runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
//添加一个额外的命令来转换脚本
//将对象输出为格式良好的字符串
//删除此行以获取实际对象
//脚本返回的值。例如,脚本
//“获取进程”返回一个集合
//系统。诊断。过程实例的。
pipeline.Commands.Add(“输出字符串”);
//执行脚本
收集结果=pipeline.Invoke();
//关闭运行空间
runspace.Close();
//将脚本结果转换为单个字符串
StringBuilder StringBuilder=新的StringBuilder();
foreach(结果中的PSObject对象)
{
stringBuilder.AppendLine(obj.ToString());
}
返回stringBuilder.ToString();
}
这种方法做得很巧妙,有适当的注释。你也可以直接去我给的代码项目的链接下载它并开始玩
private string RunScript(string scriptText)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
// add an extra command to transform the script
// output objects into nicely formatted strings
// remove this line to get the actual objects
// that the script returns. For example, the script
// "Get-Process" returns a collection
// of System.Diagnostics.Process instances.
pipeline.Commands.Add("Out-String");
// execute the script
Collection<psobject /> results = pipeline.Invoke();
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}