none
PowerShell 执行没有返回结果 RRS feed

  • 问题

  • 使用.net C#开发的一个Console程序,使用powershell去获取邮箱的通讯组

    //http://technet.microsoft.com/zh-cn/library/bb124755%28v=exchg.150%29.aspx

    "Get-DistributionGroup -ResultSize Unlimited"

    //获取组的代码:

               using (shell = PowerShell.Create())
                {
                    shell.Runspace = runspace;

                    PSCommand command = new PSCommand();
                    foreach (string scr in parms)
                    {
                        command.AddScript(scr);
                    }
                    //command.AddScript("Out-String");
                    shell.Commands = command;
                   
                    objects = shell.Invoke();
                }

    直接在VS里debug的时候,返回了所有组信息,但是直接运行生成的exe却没有返回结果,这是为什么?

    2015年1月16日 7:18

答案

全部回复

  • 有人知道这个是啥问题吗?
    2015年1月19日 1:06
  • 你好:

    能把完整代码贴出来看看吗?我想重现一下你的问题。


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2015年1月19日 9:25
    版主
  • string url = "https://partner.outlook.cn/powershell";

    RunspaceConfiguration config = null;
            Runspace runspace = null;
            PowerShell shell = null;

            public void Login(string myusername, string mypassword)
            {
                try
                {
                    System.Uri psURL = new Uri(url);
                    System.Security.SecureString securePassword = CreateSecureString(mypassword);
                    System.Management.Automation.PSCredential creds = new System.Management.Automation.PSCredential(myusername, securePassword);

                    PSCommand command = new PSCommand();

                    //command.AddArgument()
                    command.AddCommand("New-PSSession");
                    command.AddParameter("ConfigurationName", "Microsoft.Exchange");
                    command.AddParameter("ConnectionUri", psURL);
                    command.AddParameter("Credential", creds);
                    command.AddParameter("Authentication", "Basic");
                    command.AddParameter("AllowRedirection");

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


                    PowerShell shell1 = PowerShell.Create();
                    shell1.Runspace = runspace;
                    shell1.Commands = command;

                    if (runspace.RunspaceStateInfo != null && runspace.RunspaceStateInfo.State.ToString().Equals("Closed"))
                    {
                        runspace = RunspaceFactory.CreateRunspace();
                    }
                    else if (runspace.RunspaceStateInfo.State.ToString().Equals("BeforeOpen"))
                    {
                        runspace.Open();
                    }

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

                    if (result.Count == 0)
                    {
                        log.Info("PowerShellTool Login ex: " + myusername + " can't login.");
                        return;
                    }
                    Session = result[0];

                    //Session
                    shell = PowerShell.Create();
                    command = new PSCommand();
                    command.AddCommand("Set-Variable");
                    command.AddParameter("Name", "Session");
                    command.AddParameter("Value", Session);

                    shell.Commands = command;
                    shell.Runspace = runspace;
                    shell.Invoke();


                    shell = PowerShell.Create();
                    command = new PSCommand();
                    command.AddScript("Import-PSSession -Session $Session");
                    shell.Commands = command;
                    shell.Runspace = runspace;
                    shell.Invoke();

                    //Connect
                    shell = PowerShell.Create();
                    command = new PSCommand();
                    command.AddScript("import-module msonline");

                    shell.Commands = command;
                    shell.Runspace = runspace;
                    shell.Invoke();


                    shell = PowerShell.Create();
                    command = new PSCommand();
                    command.AddCommand("Connect-MsolService");
                    command.AddParameter("Credential", creds);

                    shell.Commands = command;
                    shell.Runspace = runspace;
                    shell.Invoke();
                    //log.Info("PowerShellTool Login with:" + myusername + ", " + mypassword);
                }
                catch (Exception ex)
                {
                    log.Error("PowerShellTool Login error:" + ex.Message, ex);
                    throw ex;
                }
            }

            /// <summary>
            /// Get-DistributionGroup 查询现有通讯组。
            /// http://technet.microsoft.com/zh-cn/library/bb124755%28v=exchg.150%29.aspx
            /// </summary>
            /// <returns></returns>
            public Collection<PSObject> GetDistributionGroups()
            {
                List<string> parms = new List<string>();
                parms.Add("Get-DistributionGroup -ResultSize Unlimited");
                //string filepath = Directory.GetCurrentDirectory() +@"\group.csv";
                //parms.Add("Get-DistributionGroup -ResultSize Unlimited | Export-Csv " + filepath);
                return InvokePowerShell(parms);
            }

            /// <summary>
            /// 执行PowerShell
            /// </summary>
            /// <param name="parms"></param>
            /// <returns></returns>
            Collection<PSObject> InvokePowerShell(List<string> parms)
            {
                Collection<PSObject> objects = null;
                Console.WriteLine("InvokePowerShell " + DateTime.Now.ToLocalTime());
                if (runspace.RunspaceStateInfo != null && runspace.RunspaceStateInfo.State.ToString().Equals("Closed"))
                {
                    runspace = RunspaceFactory.CreateRunspace();
                    runspace.Open();
                }
                else if (runspace.RunspaceStateInfo.State.ToString().Equals("BeforeOpen"))
                {
                    runspace.Open();
                }
                //Pipeline pipeline = runspace.CreatePipeline();
                //StringBuilder sb = new StringBuilder();
                //foreach (string scr in parms)
                //{
                //    sb.Append(scr);
                //}
                //pipeline.Commands.AddScript(sb.ToString());
                ////pipeline.Commands.Add("Out-String");
                //objects = pipeline.Invoke();

                using (shell = PowerShell.Create())
                {
                    shell.Runspace = runspace;

                    PSCommand command = new PSCommand();
                    foreach (string scr in parms)
                    {
                        command.AddScript(scr);
                    }
                    //command.AddScript("Out-String");
                    shell.Commands = command;
                   
                    objects = shell.Invoke();
                }
                //runspace.Close();

                //IAsyncResult iAsyncResult = shell.BeginInvoke();
                //do
                //{
                //    Thread.Sleep(100);
                //    Console.WriteLine(iAsyncResult.IsCompleted + " thread iAsyncResult " + iAsyncResult.CompletedSynchronously);
                //} while (!iAsyncResult.IsCompleted);
                //Thread.Sleep(8000);
                //PSDataCollection<PSObject> psObjects = shell.EndInvoke(iAsyncResult);
                //Console.WriteLine( DateTime.Now.ToLocalTime()+" thread end " + psObjects.Count);
                //foreach (PSObject ps in psObjects)
                //{
                //    Console.WriteLine(
                //    "{0,-24}{1}",
                //    ps.Members["ProcessName"].Value,
                //    ps.Members["Id"].Value);
                //}

                return objects;
            }

    2015年1月19日 9:32
  • 又测试了一下,好像在开发机(Win8)上运行生成的exe也是可以有返回结果的,但是在服务器运行(window server 2008)就没有返回结果,服务器上装了vs后,在vs里debug也是有返回结果的,执行生成的exe就是没有返回结果,服务器没有开防火墙。
    2015年1月20日 9:13
  • 你好

    单看代码 没有找到错误,你在url处和获得list数据的时候 抛出 信息框, 看看结果是否准确。

    2015年1月24日 14:38
  • 错误找到了,是少了一个执行权限,需要先执行下面的命令

    Set-ExecutionPolicy RemoteSigned -Force

    2015年1月26日 1:00