2016-10-03 101 views
1

我試圖在C#應用程序內執行此命令(列出Firefox擴展)。在C#上執行PowerShell命令行

Get-ChildItem -Path $env:USERPROFILE"\AppData\Roaming\Mozilla\Firefox\Profiles\*\extensions.json" | Get-Content 

從MSDN文檔,我想通了,應該看起來像是代碼類似

PowerShell ps = PowerShell.Create(); 
ps.AddCommand("Get-ChildItem"); 
ps.AddParameter("Path", "\"$env:USERPROFILE\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\*\\extensions.json\""); 
ps.AddCommand("Get-Content"); 
Collection<PSObject> results = ps.Invoke(); 

然而,「結果」是null(當PS線不是)。我發現了一些類似的問題,但我真的沒有辦法用它來回答這個問題。任何人都知道我該如何修復我的代碼?

回答

1

您可以嘗試使用此代碼以獲得您想要的結果。而不是使用PowerShell.Create,而是使用RunspaceInvoke.Invoke,僅使用完整命令作爲參數。希望它有幫助:

using (RunspaceInvoke invoke = new RunspaceInvoke()) 
{ 
    Collection<PSObject>result = invoke.Invoke("Get-ChildItem -Path $env:USERPROFILE\"\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\*\\extensions.json\" | Get-Content"); 
}