title: PowerShell v3 Invoke-WebRequest: Troubles with forms
body: <p>Since I upgraded to Windows 8 a lot of my PowerShell scripts relying on launching an invisible IE won’t quite work anymore, so I tried switching to the <em>Invoke-WebRequest</em> command. I did a lot of googling but still can’t get my script to work.</p>
  <p>This is what it should do:</p>
  <ol>
  <li>load up a website with a simple form (username, password, submit-button),</li>
  <li>enter the credentials</li>
  <li>and submit them.</li>
  </ol>
  <p>The <a href="http://technet.microsoft.com/en-us/library/hh849901.aspx" rel="nofollow noreferrer">Microsoft tech-net examples</a> were not very helpful for me, that is what I pieced together:</p>
  <pre><code>$myUrl = &quot;http://some.url&quot;  
  
  $response = Invoke-WebRequest -Uri $myUrl -Method Default -SessionVariable $rb
  $form = $response.Forms[0]
  $form.Fields[&quot;user&quot;]     = &quot;username&quot;
  $form.Fields[&quot;password&quot;] = &quot;password&quot;
  
  $response = Invoke-WebRequest -Uri $form.Action -WebSession $rb -Method POST 
  $response.StatusDescriptionOK
  </code></pre>
  <p>I receive two errors, the first one when trying to write into the <code>user</code> field:</p>
  <pre><code>Cannot index into a null array.
  
  $form.Fields[&quot;user&quot;]     = &quot;username&quot;
  
      + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : NullArray
  </code></pre>
  <p>The second one has to do with the <code>$form.Action</code> which I have no idea what it should read:</p>
  <pre><code>Invoke-WebRequest : Cannot validate argument on parameter 'Uri'. The argument is  null or empty. Supply an argument that is not null or empty and then try the command  again.
  </code></pre>
  <p>Again, I relied heavily on <a href="http://technet.microsoft.com/en-us/library/hh849901.aspx" rel="nofollow noreferrer">example #2 at Microsoft</a>.</p>