C#中的Powershell - 访问Exchange

时间:2017-12-19 13:57:47

标签: c# powershell syntax

我在.NET System.Management.Automation *命名空间中使用Powershell类。我需要翻译这个将变量设置为C#语法的cmdlet调用:

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection

以下是我构建命令的方法:

 List<Command> cList = new List<Command>();
 Command cEx = new Command("Set-ExecutionPolicy");
        cEx.Parameters.Add(new CommandParameter("Scope", "CurrentUser"));
        cEx.Parameters.Add(new CommandParameter("ExecutionPolicy", "Unrestricted"));
        cList.Add(cEx);

稍后,我遍历命令的cList并按如下方式执行:

Pipeline pipeline;
        Collection<PSObject> exResults = null;
        foreach (Command cmd in cList)
        {
            pipeline = ps.Runspace.CreatePipeline();
            pipeline.Commands.Add(cmd);
            exResults = pipeline.Invoke();
            foreach (PSObject p in exResults)
            {
                Console.WriteLine(p);
            }
        }

我需要帮助获得设置$ Session变量的第一个命令的语法。这是我尝试过的,但我认为不正确:

 Command c10 = new Command("Set-Variable");
        c10.Parameters.Add(new CommandParameter("Name", "Session"));
        c10.Parameters.Add(new CommandParameter("Value", "New-PSSession"));
        c10.Parameters.Add(new CommandParameter("ConfigurationName", "Microsoft.Exchange"));
        c10.Parameters.Add(new CommandParameter("ConnectionUri", "https://outlook.office365.com/powershell-liveid"));
        c10.Parameters.Add(new CommandParameter("Credential", pCredUser));
        c10.Parameters.Add(new CommandParameter("Authentication", "Basic"));
        c10.Parameters.Add(new CommandParameter("AllowRedirection"));
        cList.Add(c10);

当调用c10命令时,我得到异常:&#34;找不到与参数名称匹配的参数&#39; ConfigurationName&#39;&#34;

1 个答案:

答案 0 :(得分:0)

问题是尝试连接到Exchange 2010。

这篇文章(以及其中的文章)是有帮助的 - https://blogs.msdn.microsoft.com/akashb/2010/03/25/how-to-migrating-exchange-2007-powershell-managed-code-to-work-with-exchange-2010/