繁体   English   中英

C#powershell脚本

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM