[英]Running Powershell in C# and Powershell is behaving differently
該圖顯示了在 C# 和 Powershell ISE 中執行的相同 powershell 命令。 我的問題是,Powershell 顯示了進程和進程目錄的完整列表,但是在 C# 中執行的代碼的結果不包含像 svchost.exe 這樣的 windows 進程。
當然,我的 C# 表格和 Powershell ISE 都以管理員身份運行。 此外,我確保對我的表單進行編碼以使用管理權限啟動。 再次確定,我通過右鍵單擊執行了我的 C# - 以管理員身份運行(我也對 Powershell ISE 執行了此操作)
命令/秒:Powershell 和 C#
get-process | get-item -erroraction silentlycontinue | format-table name, directory
get-process | format-table name, directory
盡管此特定命令顯示了所有過程:
get-process
不幸的是,將它與上面的語法結合起來會顯示與 C# 不同的 output。
private string RunScript(string script)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(script);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject pSObject in results)
stringBuilder.AppendLine(pSObject.ToString());
return stringBuilder.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
output.Clear();
output.Text = RunFilePs1(input.Text);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.