简体   繁体   中英

Capturing output from powershell commands run from C#

I'm creating a simple C# program used to check various settings on windows 10 builds we're testing. I need to capture the output from a CMD or Powershell invoke and display the result as a string (human-readable). Specifically, I'm trying to capture the output from get-bitlockervolume to check if the drives are encrypted. The program should be able to run without using admin creds.

Get Powershell command's output when invoked through code unfortunately doesn't quite seem to work, so I thought I'd attempt to capture the output to a txt file and read it from there, but for some reason, the txt ends up being empty. For my latest attempts, I've ditched PowerShell and attempted to get it done using simple CMD.

Process bl = new Process();
bl.StartInfo.WindowStyle = ProcessWindowStyle.Hidden ;
bl.StartInfo.FileName = "cmd.exe";
bl.StartInfo.Arguments = @"/c manage-bde -status > C:\windows\temp\bitlockerstatus.txt";
bl.StartInfo.RedirectStandardOutput = true;
bl.StartInfo.UseShellExecute = false;
bl.Start();

This seems to create the output file I was looking for in the right location, but it always turns up empty. When running the command directly from cmd, there doesn't seem to be an issue recording the output.

I'm still quite new to C#, self-learning as I go along, so any suggestions for an alternate method/way of doing this would be appreciated.

Very late edit: I've figured out a way by using a Collection. code:

StringBuilder str = new Stringbuilder();

using (Powershell ps = Powershell.create())
     {
       ps.addscript ("manage-bde -status");
       Collection<PSObject> psoutp = ps.Invoke();

       foreach(PSObject outp in psoutp)
             {
                if (outp != null)
                   {
                      str.Append(outp);
                   }
                else str.Append ("Error");
             }

       return str.ToString();
      }

This for a Method that returns the output of manage-bde - status from powershell back to main. If there's no output at all (not even an errormessage) , it'll simply return "error" back to main. Here's hoping this helps someone else one day.

I think the answer is here :

while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM