title: Powershell Invoke-WebRequest Form Post
body: <p>I'm trying to automate submitting a web form (mainly as an exercise for learning Powershell better).</p>
  
  <p>The first thing I did was use Fiddler2 to see what EXACT webform fields (and respective values) are sent (using a regular web browser to submit the data).  </p>
  
  <p>Then, I recreated ALL possible fields and values I saw in Fiddler's WebForm tab in my Powershell script below; I included __VIEWSTATE, __EVENTVALIDATION (and their values I grabbed from the start of the websession).  I included fields that have no values (identical to what I saw in fiddler).  I even included the submit button (since I saw that in Fiddler too).</p>
  
  <p>Unfortunately, after I POST all fields using my script; when I look at $response.rawcontent (shown in script below), it's still on the same webpage I started with.  If I submit the form using my web browser, it updates the page with new information.  I'd like to know what I'm doing wrong or missing.  I originally tried POSTing the form without any of the fields that start with __  However, that didn't work.  </p>
  
  <p>PS:  When submitting the form via a web browser, I have two more fields that are greyed out (and filled in for me with my name and email address).  However, interestingly, I dont see these two fields in Fiddler.  I'm guessing they may be submitted via __VIEWSTATE or __EVENTVALIDATION encoded data?</p>
  
  <p>Thank you so much for helping me!</p>
  
  <pre><code>$UserAgent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)'
  $r=Invoke-WebRequest -Uri 'http://website.com/RTR/xl/requestform.aspx' -UseDefaultCredentials -SessionVariable RequestForm
  
  $fields = Invoke-WebRequest -Uri 'http://website.com/RTR/xl/requestform.aspx' -WebSession $RequestForm | select -ExpandProperty inputfields | select name, value
  
  $viewstate = $fields | ?{$_.name -match "VIEWSTATE"} | select -ExpandProperty value
  $eventvalidation = $fields | ?{$_.name -match "EVENTVALIDATION"} | select -ExpandProperty value
  
  #Same exact fields and values seen in Fiddler; even in the same order:    
  $form.Fields["__EVENTTARGET"] = ""
  $form.Fields["__EVENTARGUMENT"] = ""
  $form.Fields["__VIEWSTATE"] = $viewstate
  $form.Fields["__EVENTVALIDATION"] = $eventvalidation
  $form.Fields["xl$phone"] = "917-471-6784""
  $form.Fields["xl$form$Submit"] = "Submit"
  
  $response = Invoke-WebRequest -Uri 'http://website.com/RTR/xl/requestform.aspx' -WebSession $RequestForm -Method POST -Body $form.Fields -ContentType 'application/x-www-form-urlencoded'
  
  $response.rawcontent | out-file $home\response.html
  </code></pre>