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:
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.
invoke-webrequest in windows powershell (5.1) uses some IE classes to get that data / parses it. powershell (7) does not as it is not windows specific. so invoke-webrequest leads to different results in the different versions. ive seen this as well, unfortunately don't have a sample.
To create a web request session, enter a variable name, without a dollar sign, in the value of the SessionVariable parameter of an Invoke-WebRequest command. Invoke-WebRequest creates the session and saves it in the variable. In subsequent commands, use the variable as the value of the WebSession parameter.
Beginning in PowerShell 7.0, Invoke-WebRequest supports proxy configuration defined by environment variables. See the Notes section of this article. Examples Example 1: Send a web request. This example uses the Invoke-WebRequest cmdlet to send a web request to the Bing.com site.
This cmdlet was introduced in PowerShell 3.0. Beginning in PowerShell 7.0, Invoke-WebRequest supports proxy configuration defined by environment variables. See the Notes section of this article. The examples in this article reference hosts in the contoso.com domain. This is a fictitious domain used by Microsoft for examples.
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"
To address your problem with the unsigned/untrusted certificate, add the line
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
before the Invoke-WebRequest statement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With