title: Capture response on failed/401 Invoke-WebRequest
body: <p>How do I capture the output when Invoke-WebRequest hits a 500, 401, 403, etc.? When the call is successful, it stores the result in the <code>$Response</code> variable, but if I hit a 401 it throws the error but doesn't store the response.</p>
  
  <pre><code>$Response = Invoke-WebRequest -Method HEAD -Uri 'https://site.contoso.com'
  Invoke-WebRequest : The remote server returned an error: (401) Unauthorized.
  At line:1 char:13
  + $Response = Invoke-WebRequest -Method HEAD -Uri 'https://site.contoso.com' -Erro ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
      + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
  </code></pre>
  
  <p>The <code>$Response</code> variable remains null, however the endpoint is returning the 401 Unauthorized <em>and</em> headers, it's just not being captured by PowerShell since it is treating it as an exception. Piping it through Fiddler confirms this.</p>
  
  <p>Creating a request using <code>[System.Net.WebRequest]</code> has the same result when I execute <code>$Response = $WebRequest.GetResponse()</code>.</p>
  
  <p>Here's my <code>$PSVersionTable</code>.</p>
  
  <pre><code>Name                           Value                                                                                                           
  ----                           -----                                                                                                           
  PSVersion                      4.0                                                                                                             
  WSManStackVersion              3.0                                                                                                             
  SerializationVersion           1.1.0.1                                                                                                         
  CLRVersion                     4.0.30319.36373                                                                                                 
  BuildVersion                   6.3.9600.16406                                                                                                  
  PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}                                                                                            
  PSRemotingProtocolVersion      2.2   
  </code></pre>