Using C# To Return Data From PowerShell

谁说胖子不能爱 提交于 2019-12-25 10:32:08

问题


I am trying to return a PrimarySMTPAddress to a variable, in Powershell the code I run is this:

Get-Mailbox -identity UserName | select PrimarySMTPAddress

And it returns the correct value, I want to get this in my C# Code, I have done the following:

string getPrimarySMTP = "Get-Mailbox -identity " + username + "| select PrimarySMTPAddress";

var runSpace = RunspaceFactory.CreateRunspace(Utility.CreateConnectionInfo());
runSpace.Open();
var pipeline = runSpace.CreatePipeline();

pipeline.Commands.AddScript(getPrimarySMTP);
var primarySmtp = pipeline.Invoke();
runSpace.Dispose();

I would Expect this to return the same data, but it doesn't. I just get an exception:

The term 'select' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Is this the way to return values from a powershell command?


回答1:


For what version of Exchange ? for 2010 up you need to use Remote Powershell see https://msdn.microsoft.com/en-us/library/office/ff326159%28v=exchg.150%29.aspx . (even in 2007 your code would work because you haven't loaded the snapin).

Cheers Glen




回答2:


You may need to add an additional space character before the pipe. It' being concatenated to the username, with the resulting string becoming ... -identity UserName| select ..."

Here's the corrected statement:

string getPrimarySMTP = "Get-Mailbox -identity " + username + " | select PrimarySMTPAddress";



回答3:


Thanks for asking this question, it helped me to lead to the answer I needed. My code resulted in the following using RemoteRunspace to an Exchange 2013 environment:

    try
    {
        var target = new Uri(Uri);
        SecureString PSPassword = new SecureString();
        foreach (char c in ConfigurationManager.AppSettings["Password"])
        {
            PSPassword.AppendChar(c);
        }
        //var cred = (PSCredential)null;
        PSCredential cred = new PSCredential(ConfigurationManager.AppSettings["Username"], PSPassword);
        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(target, shell, cred);
        connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
        connectionInfo.OperationTimeout = 1 * 60 * 1000; // 4 minutes.
        connectionInfo.OpenTimeout = 1 * 30 * 1000; // 1 minute.
        using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo))
        {
            remoteRunspace.Open();
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.Runspace = remoteRunspace;
                powershell.AddScript(PSSnapin);
                powershell.Invoke();
                powershell.Streams.ClearStreams();
                powershell.Commands.Clear();
                Pipeline pipeline = remoteRunspace.CreatePipeline();
                Command getMailBox = new Command("Get-Mailbox");
                getMailBox.Parameters.Add("Identity", Username);
                Command cmd = new Command("Select-Object");
                string[] Parameter = new string[] { "PrimarySMTPAddress" };
                cmd.Parameters.Add("Property", Parameter);
                pipeline.Commands.Add(getMailBox);
                pipeline.Commands.Add(cmd);
                Collection<PSObject> results = pipeline.Invoke();
                primarySMTPAddress = results[0].ToString();
                primarySMTPAddress = primarySMTPAddress.ToUpper().Replace("@{PRIMARYSMTPADDRESS=", "");
                primarySMTPAddress = primarySMTPAddress.ToUpper().Replace("}", "");
            }
            remoteRunspace.Close();
        }
        return primarySMTPAddress;
    }
    catch
    {
        return "Error";
    }

Hope this helps anyone in future.



来源:https://stackoverflow.com/questions/28844580/using-c-sharp-to-return-data-from-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!