[英]Capturing output from powershell commands run from C#
我正在創建一個簡單的 C# 程序,用於檢查我們正在測試的 Windows 10 版本上的各種設置。 我需要捕獲來自 CMD 或 Powershell 調用的輸出並將結果顯示為字符串(人類可讀)。 具體來說,我試圖從 get-bitlockervolume 捕獲輸出以檢查驅動器是否已加密。 該程序應該能夠在不使用管理員憑據的情況下運行。
不幸的是, 通過代碼調用時獲取 Powershell 命令的輸出似乎不太有效,所以我想我會嘗試將輸出捕獲到 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# 還是很陌生,在我進行過程中自學,因此對於替代方法/方式的任何建議將不勝感激。
很晚的編輯:我已經找到了使用集合的方法。 代碼:
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 - status 從 powershell 的輸出返回到 main 的方法。 如果根本沒有輸出(甚至沒有錯誤消息),它只會將“錯誤”返回給 main。 希望有一天這可以幫助其他人。
我認為答案在這里:
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
// do something with line
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.