lithiium
lithiium

Reputation: 647

Executing PowerShell command lines on C#

I'm trying to execute this command inside a C# application (Lists Firefox extensions).

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

From MSDN documentation I figured out the code should looks like something like

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();

however, the "results" is null (when the PS line is not). I have found some similar questions on SO, but nothing I could really use to answer this. Anybody knows how can I fix my code?

Upvotes: 1

Views: 695

Answers (1)

Pikoh
Pikoh

Reputation: 7703

You can try this code to get the results you want.Instead of using PowerShell.Create, it's using RunspaceInvoke.Invoke, with just the full command as a parameter. Hope it helps:

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

Upvotes: 1

Related Questions