且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何调用PowerShell命令与"格式列表"和"从文件"从C#管道?

更新时间:2021-07-20 22:27:39

我已经得到了与第一嵌入式PowerShell的我写了同样的问题。我找了痕迹,但我无法找到它了。

I've got the same problem with the first embeded PowerShell I wrote. I look for a trace, but I can't find it anymore.

下面的东西为我工作,我适应您的代码:

Here is something working for me that I adapt to your code :

static void Main(string[] args)
{
  const string SHELL_URI = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
  const string COMMAND = @"get-process | format-List | Out-File -file c:\temp\jpb.txt";
  System.Uri serverUri = new Uri("http://WM2008R2ENT/powershell?serializationLevel=Full");
  PSCredential creds = (PSCredential)null; // Use Windows Authentication
  WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false,
                                                               "WM2008R2ENT",
                                                               5985,
                                                               "/wsman",
                                                               SHELL_URI,
                                                               creds);
  try
  {
    using (Runspace rs = RunspaceFactory.CreateRunspace(connectionInfo))
    {
      rs.Open();

      Pipeline pipeline = rs.CreatePipeline();

      string cmdLine;
      cmdLine = string.Format("&{{{0}}}", COMMAND);

      pipeline.Commands.AddScript(cmdLine);

      Collection<PSObject> results = pipeline.Invoke();

      rs.Close();
    }
  }
  catch (Exception ex)
  {
    System.Console.WriteLine("exception: {0}", ex.ToString());
  }
  return; 
}



要当心,我'不使用Exchange PowerShell中

Be carefull, I'am not using Exchange PowerShell

在我使用管道的例子,也许你的问题来自于您通过命令的方式。

In the example I use pipeline, perhaps your problem comes from the way you pass the command.