Setting a proxy within a powershell script that is started by a C# application

3.2k views Asked by At

I have a test .Net core 3.1 c# console app which creates a new Runspace and runs a powershell script.

var Session = InitialSessionState.CreateDefault();
Session.ImportPSModule("MicrosoftTeams");
var pool = RunspaceFactory.CreateRunspacePool(Session);
poo.Open();

using (PowerShell ps = PowerShell.Create())
{
   ps.Runspacepool = pool;
   ps.AddScript(ScriptContents);
   var x = await ps.InvokeAsync();  
}

The contents of a test powershell script looks like this

$proxyserver = "http://myproxy:8080";

[system.net.webrequest]::DefaultWebProxy = New-Object system.net.webproxy($proxyserver)
[system.net.webrequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

$pass = ConvertTo-SecureString "xxxx" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList "user",$pass
$a = get-Credential -Credential $cred
Connect-MicrosoftTeams -Credential $a

If this powershell script is launched via standard powershell session, it works as intended, being redirected to the HTTP proxy and successfully connecting. However if it's launched from within the C# application, everything works fine, apart from the fact it's not being redirected to the proxy.

I'm not sure what I'm doing wrong here. Is there a better way to achieve the proxy override?

0

There are 0 answers