다음을 통해 공유


Accessing SOAP web services with PowerShell

This quick tutorial will show you how to access a SOAP API service using PowerShell. The tutorial is quick because PowerShell makes it incredibly easy to do, thanks to the New-WebServiceProxy cmdlet in PS 3.0.

1. Fetching the SOAP methods
**
**Each service has a definition file published as an XML that shows all of the methods or functions that it accepts. This is what we will pass to the cmdlet. But most services also have an HTML frontend that whichever software they used to create their web services created. For this example, we'll use the Weather API from webservices.net. Go to http://www.webservicex.net/globalweather.asmx and you will see a typical frontend site showing you that this particular service provides two functions: GetWeather and GetCitesByCountry. For our purpose we will just use the first one. If you click on it, you will see the parameters that the function expects. In our case, we need CityName and CountryName. The order is important.

The second item we need is the actual XML description. Thankfully that page also includes a link to the XML endpoint: http://www.webservicex.net/globalweather.asmx?WSDL

2. Writing our code
**
**Using the information we found out, we can write our code. First, create the proxy connection to the XML endpoint:

PS> $weather = New-WebServiceProxy -Uri "http://www.webservicex.net/globalweather.asmx?wsdl" -Namespace WebServiceProxy

Then, we simply call our method, passing in two valid values, the city and country:

PS> [xml]$result = $weather.GetWeather("Montreal", "Canada")

Here we're casting the result as XML because we know that's what we will get back. PowerShell makes it very easy to parse and traverse XML data:

PS> $result.CurrentWeather

Location    : Montreal-Est, Canada (CWPQ) 45-38N 070-33W
Time        : Mar 26, 2008 - 12:00 PM EST / 2008.03.26 1700 UTC
Wind        :  from the W (260 degrees) at 16 MPH (14 KT) gusting to 23 MPH (20 KT):0
Temperature :  39 F (4 C)
Status      : Success

PS> $result.CurrentWeather.Temperature
39 F (4 C)

3. Conclusion

As you can see, with two lines of code we can retrieve information from a SOAP web service endpoint. One thing to note is that not all services will return XML, or provide a web frontend, so your mileage may vary.