PowerShell v3 Invoke-WebRequest:表单问题



自从我升级到Windows 8以来,许多依赖于启动不可见IE的PowerShell脚本将不再起作用,因此我尝试切换到Invoke-WebRequest命令。我做了很多谷歌搜索,但仍然无法让我的脚本工作。

这是它应该做的:

  1. 用一个简单的表格(用户名、密码、提交按钮)加载网站,
  2. 输入凭据
  3. 并提交它们。

Microsoft技术网的例子对我不是很有帮助,这就是我拼凑出来的:

$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

我收到两个错误,第一个错误是在尝试写入user字段时:

Cannot index into a null array.
$form.Fields["user"]     = "username"
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

第二个与我不知道应该读什么的$form.Action有关:

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.

同样,我严重依赖Microsoft的示例 #2。

尝试直接做帖子,例如:

$formFields = @{username='john doe';password='123'}
Invoke-WebRequest -Uri $myUrl -Method Post -Body $formFields -ContentType "application/x-www-form-urlencoded"

若要解决未签名/不受信任证书的问题,请添加该行

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

在 Invoke-WebRequest 语句之前

问题中的示例有效,但您必须在第一行中使用rb而不是$rb

$response = Invoke-WebRequest -Uri $myUrl -Method Default -SessionVariable rb

我还必须使用($myUrl + '/login')因为这是我的登录地址。

$response = invoke-webRequest -uri ($myUrl + '/login') -Method default -sessionVariable rb

在最后一行使用($myUrl + $form.Action)

$response = Invoke-WebRequest -Uri ($myUrl + $form.Action) -WebSession $rb -Method POST

如果您是我并且一直在对错误的 Web 请求进行故障排除,就我而言,我的 API 正在null -Body,那么您将想知道关于将行延续与注释交错的问题。 这

$r = iwr -uri $url `
    -method 'POST' `
    -headers $headers `
    # -contenttype 'application/x-www-form-urlencoded' ` # default
    -Body $body

请注意注释掉的行# -contenttype 'application/x-www-form-urlencoded' # default

放置注释会截断剩余的反引号行延续。 因此,就我而言,我的 Web 请求最终导致具有 0 字节有效负载的请求。

最新更新