在C#中执行Powershell命令(get-user -Identity" John Doe" | FL)

时间:2011-11-09 18:23:47

标签: c# powershell

我正在尝试在以下C#代码中执行_Get-User -Identity "John Doe" | FL_命令。

       PowerShell powershell = PowerShell.Create();
       powershell.AddCommand("get-user");
       powershell.AddParameter("Identity", UserName.Text);
       try
       {
           runspace.Open();
           powershell.Runspace = runspace;
           Collection<PSObject> results = powershell.Invoke();

           var builder = new StringBuilder();
           foreach (var psObject in results)
           {
               builder.AppendLine(psObject.ToString() + "\r\n");
           }
           ResultBox.Text = Server.HtmlEncode(builder.ToString());
       }

我在哪里添加_FL_命令?

2 个答案:

答案 0 :(得分:2)

添加每个命令时,它会添加到管道中。因此,如果您想要format-list,可以将其添加到管道中:

   powershell.AddCommand("get-user");
   powershell.AddParameter("Identity", UserName.Text);
   powershell.AddCommand("format-list");'
   //powershell.AddCommand("out-string");

但我不确定你想做什么,因为可以使用results

在C#中完成

答案 1 :(得分:-1)

我搜索了很多。您可以更改常规的PowerShell脚本而不是“WriteWhatYouWantToDo”。

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
RunspaceInvoke invo = new RunspaceInvoke(runspace);
invo.Invoke("Set-ExecutionPolicy Unrestricted");
Pipeline pipeline = runspace.CreatePipeline();

Command command = new Command("get-module -listAvailable | import-module\n" + WriteWhatYouWantToDo);

pipeline.Commands.Add(command);
pipeline.Commands.Add("Out-String");
try
{
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}

string result1 = stringBuilder.ToString();
string result = result1.Substring(0, 250); //define global scope
}
catch (Exception ex)
{

}