如何在C#中调用PowerShell脚本使用Quest Active Directory Cmdlets
在C#中调用PowerShell使用Quest Active Directory Cmdlets
我之前做AD相关系统集成的时候刚好实现过类似需求,核心思路是通过C#的PowerShell运行空间加载Quest Active Directory Cmdlets模块,然后执行自定义的脚本逻辑。下面是完整的代码示例和关键说明:
前提准备
- 确保已经安装了Quest Active Directory Cmdlets(可通过官方渠道获取安装包)
- 在你的C#项目中引用
System.Management.Automation程序集,推荐通过NuGet安装Microsoft.PowerShell.SDK包来获取相关依赖
核心代码实现
下面的RunScript方法封装了创建PowerShell运行空间、执行脚本、处理输出的完整流程:
using System; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Runspaces; public class PowerShellAdHelper { public static string RunScript(string scriptText) { // 1. 创建PowerShell运行空间配置 var runspaceConfiguration = RunspaceConfiguration.Create(); // 2. 加载Quest Active Directory Cmdlets模块 var snapIn = runspaceConfiguration.AddPSSnapIn("Quest.ActiveRoles.ADManagement", out var snapInException); if (snapInException != null) { throw new InvalidOperationException("无法加载Quest AD模块", snapInException); } // 3. 打开运行空间 using (var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration)) { runspace.Open(); // 4. 创建PowerShell管道并传入脚本 using (var pipeline = runspace.CreatePipeline()) { pipeline.Commands.AddScript(scriptText); // 可选:添加输出格式化命令,将结果转为字符串 // 如果需要获取脚本返回的实际AD对象(如用户、组),请移除这一行 pipeline.Commands.Add("Out-String"); // 5. 执行脚本并获取结果 Collection<PSObject> results = pipeline.Invoke(); // 6. 处理执行中的错误 if (pipeline.Error.Count > 0) { var errorMessage = string.Empty; foreach (var error in pipeline.Error.ReadToEnd()) { errorMessage += error.ToString() + Environment.NewLine; } throw new InvalidOperationException("脚本执行出错:" + errorMessage); } // 7. 将结果拼接为字符串返回 var stringBuilder = new System.Text.StringBuilder(); foreach (var obj in results) { stringBuilder.AppendLine(obj.ToString()); } return stringBuilder.ToString(); } } } }
关键说明
- 模块加载:代码中通过
AddPSSnapIn加载Quest.ActiveRoles.ADManagement模块,这是Quest AD Cmdlets的核心模块,如果加载失败需要检查模块是否正确安装,或者是否在PowerShell的可用快照列表中 - 输出处理:代码里默认添加了
Out-String命令,目的是把PowerShell的输出转为格式化的文本字符串。如果你的需求是获取脚本返回的实际AD对象(比如UserObject、GroupObject),直接移除这一行,然后通过results集合中的PSObject来访问对象的属性(比如obj.Properties["Name"].Value) - 权限注意:运行该程序的Windows账号需要具备对应的Active Directory操作权限,Quest Cmdlets的权限逻辑和原生AD操作一致
- 示例调用:比如你要查询AD中的所有用户,可以这样调用:
var script = "Get-QADUser -SearchRoot 'DC=contoso,DC=com'"; var result = PowerShellAdHelper.RunScript(script); Console.WriteLine(result);
内容的提问来源于stack exchange,提问作者scharette
相关产品推荐
相关产品推荐

