raithedavion
raithedavion

Reputation: 127

Running Powershell "IEX" from C#

I am trying to automate the running of a powershell script along with the running of other programs.

To run the powershell script manually, I would normally do this in a command prompt:

powershell "IEX (New-Object Net.WebClient).DownloadString('http://serverurl/Script.ps1'); Invoke-Method"

I can't seem to replicate this in c# to save my life using built in "PowerShell" commands. I"d rather NOT have to use things like "Process", so any advice would be helpful.

Upvotes: 0

Views: 1772

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

Since System.Net.WebClient is a .NET class, you don't need PowerShell to use it:

string script = (new System.Net.WebClient()).DownloadString('http://serverurl/Script.ps1');

To execute the script, use the System.Management.Automation.PowerShell class:

using System.Management.Automation;
// ...

using(PowerShell ps = PowerShell.Create())
{
    ps.AddScript(script).AddScript("Invoke-Method");
    ps.Invoke();
}

Upvotes: 1

Related Questions