【问题标题】:PowerShell v3 Invoke-WebRequest: Troubles with formsPowerShell v3 Invoke-WebRequest:表单问题
【发布时间】:2012-12-05 17:55:28
【问题描述】:

自从我升级到 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.

再次,我非常依赖example #2 at Microsoft

【问题讨论】:

    标签: forms powershell web webrequest


    【解决方案1】:

    尝试直接发帖,例如:

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

    【讨论】:

    • 感谢您的建议,基思。我刚刚尝试过,但我遇到了更多麻烦。首先,我需要克服证书错误才能到达登录表单。我现在在浏览器中手动覆盖了这个,但是在登录页面上我得到任何 Invoke-WebRequest 的以下错误:Could not establish trust relationship for the SSL/TLS secure channel....
    【解决方案2】:

    要解决您对未签名/不受信任证书的问题,请添加以下行

    [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') - 方法默认值 -SessionVariable rb

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

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

      【讨论】:

        【解决方案4】:

        如果您是我,并且一直在对错误的 Web 请求进行故障排除,在我的情况下,-Body 在我的 API 中变成了null,那么您将想了解关于交错行延续的问题与 cmets。这个

        $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 字节有效负载的请求。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-07-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-28
          • 1970-01-01
          • 1970-01-01
          • 2020-03-17
          相关资源
          最近更新 更多