C#执行PowerShell调用Grant-CsTenantDialPlan时遇空引用错误
在C#中执行PowerShell脚本调用Grant-CsTenantDialPlan命令时,出现“对象引用未设置为对象实例”错误。代码如下:
PowerShell ps = PowerShell.Create(); PSCommand cmd1 = new PSCommand(); cmd1.AddCommand("Grant-CsTenantDialPlan") .AddParameter("Identity", "xxxx.yyyy@xxxxx.com.tr") .AddParameter("PolicyName", "DialPlan-GMMA"); ps.Commands = cmd1; ps.Invoke();
已确认PolicyName参数不为空,但仍触发错误,错误堆栈信息:
at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork(Runspace rs, Boolean performSyncInvoke)
at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, Boolean isSync)
at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection1 input, PSDataCollection1 output, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection1 input, PSDataCollection1 output, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.Invoke(IEnumerable input, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.Invoke()
at ConnectTeams.Program.Main(String[] args) in C:\Projects\ConnectTeams\ConnectTeams\Program.cs:line 120
未初始化有效Runspace:默认创建的PowerShell实例没有关联已认证的Runspace,调用
Invoke()时内部创建Runspace失败,导致空引用。Teams相关命令需要先完成租户认证,不能直接使用无权限的默认Runspace。
解决:手动创建并配置已认证的Runspace,比如通过OAuth获取认证凭据后初始化Runspace,再关联到PowerShell实例。Teams模块未加载:
Grant-CsTenantDialPlan属于MicrosoftTeams模块,若PowerShell环境中未加载该模块,添加命令时无法找到对应指令,后续执行触发空引用。
解决:添加目标命令前,先执行AddCommand("Import-Module").AddParameter("Name", "MicrosoftTeams")加载模块,确保命令能被识别。参数有效性问题:虽然
PolicyName不为空,但Identity对应的用户不存在,或PolicyName指定的拨号计划不存在,导致命令内部逻辑抛出空引用。
解决:先在本地PowerShell中执行相同命令,验证用户和拨号计划的有效性,确认参数格式和内容正确。未捕获PowerShell错误流:代码没有读取
ps.Streams.Error集合,空引用可能是命令执行时的其他错误引发的,真正的问题被隐藏。
解决:调用Invoke()后,遍历ps.Streams.Error获取具体错误信息,这是定位问题最直接的方式。
内容的提问来源于stack exchange,提问作者mgk

