PowerShell v3 Invoke-WebRequest: Troubles with forms
Solution 1
Try doing the post directly e.g.:
$formFields = @{username='john doe';password='123'}
Invoke-WebRequest -Uri $myUrl -Method Post -Body $formFields -ContentType "application/x-www-form-urlencoded"
Solution 2
To address your problem with the unsigned/untrusted certificate, add the line
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
before the Invoke-WebRequest statement
Solution 3
The example in the question works, but you have to use rb
and not $rb
in the first line:
$response = Invoke-WebRequest -Uri $myUrl -Method Default -SessionVariable rb
I also had to use ($myUrl + '/login')
since this is my login address.
$response = Invoke-WebRequest -Uri ($myUrl + '/login') -Method Default -SessionVariable rb
And in the last line used ($myUrl + $form.Action)
:
$response = Invoke-WebRequest -Uri ($myUrl + $form.Action) -WebSession $rb -Method POST
Phil Strahl
Updated on September 15, 2021Comments
-
Phil Strahl over 2 years
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 Invoke-WebRequest command. I did a lot of googling but still can’t get my script to work.
This is what it should do:
- load up a website with a simple form (username, password, submit-button),
- enter the credentials
- and submit them.
The Microsoft tech-net examples were not very helpful for me, that is what I pieced together:
$myUrl = "http://some.url" $response = Invoke-WebRequest -Uri $myUrl -Method Default -SessionVariable $rb $form = $response.Forms[0] $form.Fields["user"] = "username" $form.Fields["password"] = "password" $response = Invoke-WebRequest -Uri $form.Action -WebSession $rb -Method POST $response.StatusDescriptionOK
I receive two errors, the first one when trying to write into the
user
field:Cannot index into a null array. $form.Fields["user"] = "username" + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : NullArray
The second one has to do with the
$form.Action
which I have no idea what it should read: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.
Again, I relied heavily on example #2 at Microsoft.
-
Phil Strahl over 11 yearsThanks for the suggestion, Keith. I just tried it, but I came across some more troubles. First of all, I need to get past a certificate error to even reach the login-form. I did this override manually in a browser for now, yet on the login-page I get for any Invoke-WebRequest the following error:
Could not establish trust relationship for the SSL/TLS secure channel.
…