C#代码(Source):
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; DR
脚本正常运行但是对Quest cmdlet的调用不起作用,因为它不返回任何内容(或者在上面的示例中为0)。有什么我想念的吗?
修改
需要注意的是,在Powershell中运行的完全相同的脚本会返回正确的值。从C#调用它不会。