0

C# 代码来源):

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();
}

Powershell 代码

#Dummy code for example purpose

ASNP Quest*
#Example of cmdlet I want to use
$Users = Get-QADGroupMember -Identity $Group -Enabled
return $Users.count

如您所见,我的目标是在我的 WPF 应用程序中调用RunScript上面使用的脚本。Button_Click event我已经能够正确调用脚本,但是对 Quest cmdlet 的调用显然没有按预期进行,因为在上面的示例中我会收到 0。

TL;博士

脚本运行正常,但对 Quest cmdlet 的调用不起作用,因为它不返回任何内容(或在上面的示例中为 0)。有什么我想念的吗?

编辑

需要注意的是,在 Powershell 中运行的完全相同的脚本会返回正确的值。从 C# 调用它不要。

4

0 回答 0