[英]C# powershell scripting
我知道如何執行單個powershell命令並使用C#代碼查看它的結果。 但我想知道如何執行如下的一組相關命令並獲得輸出:
$x = some_commandlet
$x.isPaused()
簡單地說,我想訪問$x.isPaused()
的返回值。
如何將此功能添加到我的C#應用程序?
對於這樣的命令,最好創建一個名為pipeline的東西並將其提供給你的腳本。 我找到了一個很好的例子。 您可以在此處找到有關此代碼和此類項目的更多信息 。
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();
}
這種方法很好地完成了正確的評論。 您也可以直接轉到Code Project的鏈接我下載並開始播放!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.