PowerShell v3 调用 Web 请求:处理表单时出现问题

16

自从我升级到Windows 8后,我依赖于启动一个隐形IE的大量PowerShell脚本无法正常工作,因此我尝试切换到Invoke-WebRequest命令。我搜索了很多但仍然无法让我的脚本工作。

这是它应该做的事情:

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

Microsoft tech-net examples 对我没有太大帮助,以下是我整理出来的:

$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

4个回答

16

尝试直接进行发布,例如:

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

感谢您的建议,Keith。我刚刚尝试了一下,但遇到了更多麻烦。首先,我需要解决证书错误才能到达登录页面。目前我已经在浏览器中手动覆盖了此项设置,在登录页面上无论是使用任何 Invoke-WebRequest 命令都会出现以下错误:无法建立安全连接的 SSL/TLS 信任关系。... - Phil Strahl

7
为了解决您遇到的未签名/不受信任证书问题,请添加以下行:

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

在执行 Invoke-WebRequest 语句之前


3

这个问题中的示例可以正常工作,但是在第一行必须使用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

0
如果你和我一样在解决一个糟糕的Web请求问题,比如我的API中的一个-Body变成了null,那么你会想知道一个坑点,就是在行续行与注释之间交错的问题。
$r = iwr -uri $url `
    -method 'POST' `
    -headers $headers `
    # -contenttype 'application/x-www-form-urlencoded' ` # default
    -Body $body

请注意被注释掉的行 # -contenttype 'application/x-www-form-urlencoded' # default 添加注释会截断剩余的反引号行继续。因此,在我的情况下,我的网络请求最终变成了一个没有有效负载的请求。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接