如何从.Net程序运行Import-PSSessions

时间:2014-02-06 15:54:11

标签: c# powershell powershell-v2.0

我正在尝试用C#编写代码,通过Power Shell命令从用户那里获取邮箱详细信息。

power shell命令脚本是:

Import-PSSession -session (New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://myServer.myDomain.com/Powershell)
Get-Mailbox -Identity helpdesk

脚本从PowerShell运行正常。

现在我的目标是使用C#运行它。

这是我的功能:

private void button1_Click(object sender, EventArgs e)  
{
    m_RunSpace = RunspaceFactory.CreateRunspace();

    m_RunSpace.Open();

    Pipeline pipeLine = m_RunSpace.CreatePipeline();

    Command newSession = new Command("New-PSSession");
    newSession.Parameters.Add("-ConfigurationName", "Microsoft.Exchange");
    newSession.Parameters.Add("-ConnectionUri", "http://myServer.myDomain.com/Powershell");

    Command createSessionForExch = new Command("Import-PSSession");
    createSessionForExch.Parameters.Add("-Session", newSession);

    Command getMailbox = new Command("Get-Mailbox");
    getMailbox.Parameters.Add("-Identity", "helpdesk");

    pipeLine.Commands.Add(createSessionForExch);
    pipeLine.Commands.Add(getMailbox);

    Collection<PSObject> commandResults = pipeLine.Invoke();

    foreach (PSObject cmdlet in commandResults)
    {


    }
}

但是我收到一条错误,指出“Get-Mailbox”命令无法识别: enter image description here

可能是因为没有正确调用Import-PSSessions。

我需要帮助如何正确地从C#

运行命令Import-PSSession

3 个答案:

答案 0 :(得分:1)

希望你找到了解决方案。如果没有,请尝试使用此代码:

 String url = "http://" + ExchangeServerName + "/powershell?serializationLevel=Full";
        System.Uri uri = new Uri(url);
        Console.WriteLine(url);
        System.Security.SecureString securePassword = String2SecureString(password);

        System.Management.Automation.PSCredential creds = new System.Management.Automation.PSCredential(userName, securePassword);


        Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();

        PowerShell powershell = PowerShell.Create();
        PSCommand command = new PSCommand();
        command.AddCommand("New-PSSession");


        command.AddParameter("ConfigurationName", "Microsoft.Exchange");
        command.AddParameter("ConnectionUri", uri);

        command.AddParameter("Credential", creds);
        command.AddParameter("Authentication", Authentication);
        //PSSessionOption sessionOption = new PSSessionOption();
        //sessionOption.SkipCACheck = true;
        //sessionOption.SkipCNCheck = true;
        //sessionOption.SkipRevocationCheck = true;
        //command.AddParameter("SessionOption", sessionOption);

        powershell.Commands = command;

        try
        {
            runspace.Open();

            powershell.Runspace = runspace;

            Collection<PSSession> result = powershell.Invoke<PSSession>();

            foreach (ErrorRecord current in powershell.Streams.Error)
                Console.WriteLine("The following Error happen when opening the remote Runspace: " + current.Exception.ToString() +
                                                                            " | InnerException: " + current.Exception.InnerException);

            if (result.Count != 1)
                throw new System.Exception("Unexpected number of Remote Runspace connections returned.");

            // Set the runspace as a local variable on the runspace
            powershell = PowerShell.Create();

            command = new PSCommand();
            command.AddCommand("Set-Variable");
            command.AddParameter("Name", "ra");
            command.AddParameter("Value", result[0]);
            powershell.Commands = command;
            powershell.Runspace = runspace;
            powershell.Invoke();

            // First import the cmdlets in the current runspace (using Import-PSSession)
            powershell = PowerShell.Create();
            command = new PSCommand();
            //command.AddScript("Import-PSSession $ra");
            command.AddScript("Invoke-Command -ScriptBlock { Get-Mailbox -Identity:" + MailBoxName + " } -Session $ra");
            powershell.Commands = command;
            powershell.Runspace = runspace;
            //powershell.Commands.AddCommand("Import-Module").AddArgument("activedirectory");
            powershell.Invoke();

            //command = new PSCommand();
            //command.AddCommand("Get-Mailbox");

            ////Change the name of the database

            //command.AddParameter("Identity", "");

            //powershell.Commands = command;
            //powershell.Runspace = runspace;


            Collection<PSObject> results = new Collection<PSObject>();
            results = powershell.Invoke();

答案 1 :(得分:1)

完整有趣的教程:Access Exchange Online by PowerShell in C#

步骤3中的Get-Mailbox示例。

答案 2 :(得分:0)

使用WSManConnectionInfo类提供uri,架构以打开远程运行空间。请找到代码:

    private static string CreateConnection()
    {
        Runspace remoteRunspace = null;



        openRunspace(
            "https://pod51057psh.outlook.com/powershell-liveid?PSVersion=3.0",
            "http://schemas.microsoft.com/powershell/Microsoft.Exchange",
            @"xxx@xxx.com",
            "xxxxx",
            ref remoteRunspace
         );

         // Command getLicenseCommand = new Command("Get-MsolAccountSku");
            //Command activityCommand = new Command("Get-GroupActivityReport");
            //activityCommand.Parameters.Add(new CommandParameter("ReportType", "Daily"));
            //activityCommand.Parameters.Add(new CommandParameter("StartDate", "03/4/2014"));
            //activityCommand.Parameters.Add(new CommandParameter("EndDate", "03/27/2014"));

        Command activityCommand = new Command("Get-Mailbox");
        activityCommand.Parameters.Add("-Identity", "xxx");

        StringBuilder stringBuilder = new StringBuilder();
        using (PowerShell powershell = PowerShell.Create())
        {
            powershell.Runspace = remoteRunspace;
            powershell.Commands.AddCommand(activityCommand);

            powershell.Invoke();
            var results = powershell.Invoke();
            remoteRunspace.Close();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
        }
        remoteRunspace.Close();
        return stringBuilder.ToString();


    }
    public static void openRunspace(string uri, string schema, string username, string livePass,   ref Runspace remoteRunspace)
    {
        System.Security.SecureString password = new System.Security.SecureString();
        foreach (char c in livePass.ToCharArray())
        {
            password.AppendChar(c);
        }
        PSCredential psc = new PSCredential(username, password);
        WSManConnectionInfo rri = new WSManConnectionInfo(new Uri(uri), schema, psc);

        rri.AuthenticationMechanism = AuthenticationMechanism.Basic;

        remoteRunspace = RunspaceFactory.CreateRunspace(rri);
        remoteRunspace.Open();
    }