在 C# 中运行 powershell 命令时会出现错误,“无法调用此函数,因为当前主机未实现它”
我有一个应用程序,用于在 C# 代码中运行 Exchange Powershell 命令,如下所示。这是我用来运行 powershell 命令的相关行的示例。
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
//load Exchange shell
rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);
Runspace runSpace = RunspaceFactory.CreateRunspace(rsConfig);
//open runspace
runSpace.Open();
//setup pipeline
Pipeline pipeLine = runSpace.CreatePipeline();
String sScript = "get-mailbox -identity 'rj'";
//add script to pipeline
pipeLine.Commands.AddScript(sScript);
//run the script
pipeLine.Invoke();
pipeLine.Dispose();
到目前为止,这段代码在所有情况下都能完美运行。我尝试运行的脚本(而不是上面的脚本)是为邮箱设置 RetentionPolicy。我尝试运行的脚本如下所示:
Set-Mailbox -Identity 'rj' -RetentionPolicy 'Main Campus Retention Policy'
当我在 powershell 本身中运行此脚本时,它运行良好,但当我尝试使用下面的代码运行它时,我得到错误,“无法调用此函数,因为当前主机未实现它。”
从这个错误来看,在 C# 中运行的命令几乎无法运行 RetentionPolicy 命令,但这没有多大意义。我已经用谷歌搜索过这个并尝试了所有建议的东西,但没有运气。
如果有人知道为什么会发生这种情况,那将会非常有帮助。
I have an application that I use to run Exchange Powershell commands inside C# code like below. This is an example of the relevant lines I use to run the powershell command.
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
//load Exchange shell
rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);
Runspace runSpace = RunspaceFactory.CreateRunspace(rsConfig);
//open runspace
runSpace.Open();
//setup pipeline
Pipeline pipeLine = runSpace.CreatePipeline();
String sScript = "get-mailbox -identity 'rj'";
//add script to pipeline
pipeLine.Commands.AddScript(sScript);
//run the script
pipeLine.Invoke();
pipeLine.Dispose();
This code works perfect in all cases until now. the script I am trying to run instead of the one above is to set the RetentionPolicy for a mailbox. The script I am trying to run looks like this:
Set-Mailbox -Identity 'rj' -RetentionPolicy 'Main Campus Retention Policy'
When I run this in powershell itself it works perfectly but when I try to run it using the code below I get the error, "Cannot invoke this function because the current host does not implement it."
From this error, it almost seems like the command that runs in C# cannot run the RetentionPolicy command but that doesn't make much sense. I have Googled this and tried everything suggested but no luck.
If anyone knows why this is happening, it would be very helpful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果该命令通常会提示确认,那么您将需要:
-Confirm:$false
作为参数(也可能是-Force
)$ConfirmPreference = "None"
在调用 Set-Mailbox 之前(也可能是-Force
)If that command would normally prompt for confirmation then you will need to either:
-Confirm:$false
as a parameter (and possibly-Force
as well)$ConfirmPreference = "None"
before calling Set-Mailbox (and possibly-Force
too)