[英]C# powershell scripting
I know how to execute a single powershell command and view the results of it using C# code. 我知道如何执行单个powershell命令并使用C#代码查看它的结果。 But I want to know how to execute a set of related commands as below and get the output:
但我想知道如何执行如下的一组相关命令并获得输出:
$x = some_commandlet
$x.isPaused()
Simply, I want to access the return value of $x.isPaused()
. 简单地说,我想访问
$x.isPaused()
的返回值。
How do I add this functionality to my C# application? 如何将此功能添加到我的C#应用程序?
For such commands, it is better that you create something called pipeline and feed it your script. 对于这样的命令,最好创建一个名为pipeline的东西并将其提供给你的脚本。 I have found a good example of this.
我找到了一个很好的例子。 You can find further about this code and such projects here .
您可以在此处找到有关此代码和此类项目的更多信息 。
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();
}
This method is neatly done with proper comments. 这种方法很好地完成了正确的评论。 Also you can directly go to the link of Code Project I gave download it and start playing!
您也可以直接转到Code Project的链接我下载并开始播放!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.