PowerShell WebRequest fails on TeamCity with HTTP-400 error

I have a powershell script that makes a SOAP call to an API:

    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
     
    $request = [System.Net.WebRequest]::Create("https://***.***.***.***/iControl/iControlPortal.cgi")
    $request.Method = "POST"
    $request.Credentials = new-object System.Net.NetworkCredential @("username", "password")
    $request.Proxy = new-object System.Net.WebProxy @("***.***.***.***", ****)
    $request.PreAuthenticate = $true;
    $request.CachePolicy = new-object System.Net.Cache.RequestCachePolicy "NoCacheNoStore"

    $payload = '<?xml version="1.0"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"><soap:Body><q1:get_monitor_status xmlns:q1="urn:iControl:LocalLB/PoolMember"><pool_names href="#id1" /></q1:get_monitor_status><soapenc:Array id="id1"><Item>{0}</Item></soapenc:Array></soap:Body></soap:Envelope>' -f "my-pool"
    $requestPayloadWriter = new-object System.IO.StreamWriter $request.GetRequestStream()
    $requestPayloadWriter.Write($payload)
    $requestPayloadWriter.Flush()
    $requestPayloadWriter.Close()

    $responsePayloadReader = new-object System.IO.StreamReader $request.GetResponse().GetResponseStream()
    $pool_status = $responsePayloadReader.ReadToEnd()
    $responsePayloadReader.Flush()
    $responsePayloadReader.Close()

    $pool_status

This works locally on my machine, but fails when I run it via TeamCity.
It does work when I remote into the agent and run script manually from the console.

Any suggestions on what could be going wrong or how to diagnose this further?
I was not able to capture any traffic using Fiddler, so any suggestions on that are also welcome.

Please sign in to leave a comment.