PowerShell v3 Invoke-WebRequest: Troubles with forms
自从我升级到Windows 8以来,很多我的PowerShell脚本都依赖于启动一个不可见的IE来工作,所以我尝试切换到Invoke-WebRequest命令。我做了很多谷歌搜索,但仍然无法使我的脚本正常工作。
这是应该做的:
借助令人难以置信的糟糕的Microsoft技术网示例的帮助(至少对我来说),我将以下内容拼凑而成:
1 2 3 4 5 6 7 8 9 | $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 |
我收到两个错误,尝试写入"用户"字段时出现第一个错误:
Cannot index into a null array.
$form.Fields["user"] ="username"
1
2 + CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
第二个与
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。
编辑:感谢hammar的大写。我的举止在哪里? ;)
尝试直接发布信息,例如:
1 2 | $formFields = @{username='john doe';password='123'} Invoke-WebRequest -Uri $myUrl -Method Post -Body $formFields -ContentType"application/x-www-form-urlencoded" |
要解决未签名/不受信任的证书的问题,请添加行
1 | [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} |
在Invoke-WebRequest语句之前
问题中的示例有效,但您必须在第一行中使用
1 | $response = Invoke-WebRequest -Uri $myUrl -Method Default -SessionVariable rb |
我还必须使用
$ response =调用WebRequest -Uri($ myUrl'/ login')-方法默认值-SessionVariable rb
最后一行使用
1 | $response = Invoke-WebRequest -Uri ($myUrl + $form.Action) -WebSession $rb -Method POST |
如果您是我,并且一直在对错误的Web请求进行故障排除,例如我的API中的
1 2 3 4 5 | $r = iwr -uri $url ` -method 'POST' ` -headers $headers ` # -contenttype 'application/x-www-form-urlencoded' ` # default -Body $body |
注意注释行
放置注释会截断其余的反引号继续。因此,在我的情况下,我的Web请求最终以有效载荷为0字节的请求结束。