我正在创建一个简单的C#程序,用于检查我们正在测试的Windows 10版本上的各种设置。我需要捕获CMD或Powershell调用的输出,并将结果显示为字符串(人类可读)。具体来说,我试图从get-bitlockervolume捕获输出以检查驱动器是否已加密。该程序应该能够在不使用管理员身份的情况下运行。
Get Powershell command's output when invoked through code 不幸的是,它似乎并不能正常工作,因此我想尝试将输出捕获到txt文件并从那里读取它,但是由于某种原因,txt最终为空。对于我的最新尝试,我放弃了PowerShell,并尝试使用简单的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();
这似乎可以在正确的位置创建我一直在寻找的输出文件,但是它总是变成空的。直接从cmd运行命令时,记录输出似乎没有问题。
我对C#还是很陌生,可以自学,因此建议您选择其他方法/方式。
非常晚的编辑: 我想出了一个使用Collection的方法。 代码:
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();
}
此方法用于将manage-bde-状态从powershell返回的输出返回到main。如果根本没有输出(甚至没有错误消息),它只会将“错误”返回到main。 希望有一天能对其他人有所帮助。
答案 0 :(得分:0)
我认为答案是here:
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
// do something with line
}