[英]How can I start a script in Exchange Management Shell from C#?
I am creating a website with which you can create room mailboxes. 我正在创建一个网站,您可以使用它创建会议室邮箱。 Once you click on "Create", a PowerShell-Script is built in C# (as a string).
单击“创建”后,将使用C#(作为字符串)构建PowerShell-Script。 Now how do I start the Exchange Management Shell and execute that script?
现在如何启动Exchange命令行管理程序并执行该脚本?
I've tried Process.Start(EMSfilePath, scriptToBeExecuted)
, however the EMS is a shortcut (.lnk file) and Process.Start doesn't like that. 我已经尝试过
Process.Start(EMSfilePath, scriptToBeExecuted)
,但是EMS是快捷方式(.lnk文件),而Process.Start不喜欢这样。 When I look at the target of that shortcut I see that powershell.exe is started with a couple of parameters. 当我查看该快捷方式的目标时,我看到powershell.exe是用几个参数启动的。 If I try
Process.Start("powershell.exe", coupleOfParameters
), the EMS does get opened, however I don't know how to now pass my script in there. 如果尝试使用
Process.Start("powershell.exe", coupleOfParameters
),则EMS确实会打开,但是我现在不知道如何在其中传递脚本。 Please help 请帮忙
I've used this C# example code in the past to manage on-premises Exchange Server: 我过去曾使用此C#示例代码来管理本地Exchange Server:
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Security;
private static Runspace OpenExchangeManagementRunspace(
string url,
AuthenticationMechanism authenticationMechanism = AuthenticationMechanism.Kerberos,
string userName = null,
string password = null)
{
Runspace runspace = null;
WSManConnectionInfo shellConnection = null;
PSCredential shellCred = null;
// Username and password is optional when using Kerberos authentication
if (!string.IsNullOrWhiteSpace(userName) &&
!string.IsNullOrWhiteSpace(password))
{
var securePassword = ConvertToSecureString(password);
shellCred = new PSCredential(userName, securePassword);
}
shellConnection = new WSManConnectionInfo(new Uri(url), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", shellCred);
shellConnection.AuthenticationMechanism = authenticationMechanism;
// This will take some time
runspace = RunspaceFactory.CreateRunspace(shellConnection);
runspace.Open();
return runspace;
}
// USAGE:
// URL for Office365:
// https://outlook.office365.com/powershell-liveid/
//
// URL for on-premises Exchange server:
// http://hostname/powershell?serializationLevel=Full;clientApplication=MyAppName
//
using (Runspace remoteRunspace = OpenExchangeManagementRunspace("https://example.com/powershell?serializationLevel=Full;clientApplication=MyExampleAppName"))
using (PowerShell shell = PowerShell.Create())
{
shell.Runspace = remoteRunspace;
// Run some commands:
shell
.AddCommand("Get-Mailbox")
.AddParameter("Identity", "example@example.com")
.Invoke();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.