Execute a SOAP request from Powershell

Tags: powershell

Web services are everywhere such as SOAP requests, WCF services and traditional ASMX asp.net web services.   I was working on a task recently we needed to call a SOAP service from a powershell script.  A good friend of mine passed this snippet to me.  If you want to test SOAP requests, using SOAP UI  This allows you to build soap requests.   Hope this helps.

These return XML objects with the server’s response.

function Execute-SOAPRequest
(
        [Xml]    $SOAPRequest,
        [String] $URL
)
{
        write-host “Sending SOAP Request To Server: $URL”
        $soapWebRequest = [System.Net.WebRequest]::Create($URL)
        $soapWebRequest.Headers.Add(“SOAPAction”,”`”`””)

        $soapWebRequest.ContentType = “text/xml;charset=`”utf-8`””
        $soapWebRequest.Accept      = “text/xml”
        $soapWebRequest.Method      = “POST”
       
        write-host “Initiating Send.”
        $requestStream = $soapWebRequest.GetRequestStream()
        $SOAPRequest.Save($requestStream)
        $requestStream.Close()
       
        write-host “Send Complete, Waiting For Response.”
        $resp = $soapWebRequest.GetResponse()
        $responseStream = $resp.GetResponseStream()
        $soapReader = [System.IO.StreamReader]($responseStream)
        $ReturnXml = [Xml] $soapReader.ReadToEnd()
        $responseStream.Close()
       
        write-host “Response Received.”

        return $ReturnXml
}

function Execute-SOAPRequestFromFile
(
        [String] $SOAPRequestFile,
        [String] $URL
)
{
        write-host “Reading and converting file to XmlDocument: $SOAPRequestFile”
        $SOAPRequest = [Xml](Get-Content $SOAPRequestFile)

        return $(Execute-SOAPRequest $SOAPRequest $URL)
}

Enjoy,

Steve Schofield
Microsoft MVP – IIS

2 Comments

  • Ozzie said

    With the release of Powershell v3 a really easier way to post a SOAP request is available. For details, you can visit this post: http://rambletech.wordpress.com/2011/09/21/posting-soap-request-from-windows-powershell/

Add a Comment