PowerShell で HTTP リクエストを送る

Windows でも curl みたいな手軽にコマンドラインから HTTP リクエストを送るツールが欲しい、 って思っていたら PowerShell にあった。 Invoke-WebRequest と Invoke-RestMethod がそう。 使い方は両方とも似ているので、Invoke-RestMethod を使って SOAP サービスを呼び出してみた。

$body = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <insertData xmlns="http://tempuri.org/">
      <request>
        <number>10</number>
        <name>本田</name>
        <age>29</age>
        <team>AC ミラン</team>
        <position>MF</position>
      </request>
    </insertData>
  </soap:Body>
</soap:Envelope>'
$url = 'http://localhost/SampleService/SampleService.asmx'
$headers = @{ 'SOAPAction' = 'http://tempuri.org/insertData' }
$xml = Invoke-RestMethod -Method Post -Uri $url -Headers $headers -Body $body -ContentType 'text/xml; charset=utf8'
$xml.InnerXml

Invoke-RestMethod で SOAP サービス呼び出すってギャグみたいだな。