我有此脚本可以成功登录网站并执行查询:
$credential = Get-Credential
$postParams = @{username=$credential.UserName;password=$credential.GetNetworkCredential().password}
Invoke-WebRequest -Uri http://www.nexusmods.com/newvegas/sessions/?Login -Method POST -Body $postParams -SessionVariable cookie
$query = Invoke-WebRequest -Uri http://www.nexusmods.com/newvegas/mods/searchresults/? -WebSession $cookie
我正在尝试与另一个网站Trello做类似的事情。这是脚本:
$credential = Get-Credential
$postParams = @{method='password';'factors[user]'=$credential.UserName;'factors[password]'=$credential.GetNetworkCredential().password}
Invoke-WebRequest -Uri https://trello.com/1/authentication -Method POST -Body $postParams -SessionVariable cookie
$result = Invoke-WebRequest -uri https://trello.com/ -WebSession $cookie
但是,结果变量显示页面就像用户未登录一样,因此我假设 session 未正确保存。我怎样才能解决这个问题?
最佳答案
如果要使用Web上的远程服务,最简单的方法是使用其API。所以这是走那条路的方法。
第1步在此处注册API:https://trello.com/app-key
在下面的代码中将此键复制为$trelloKey
。
步骤2下载已定制为与Trello一起使用的 Show-OAuthWindow
function。
$trellokey ='redacted'
$r = Show-OAuthWindow "https://trello.com/1/authorize?expiration=never&scope=read,write,account&response_type=token&name=Server%20Token&key=$trellokey"
$me = invoke-restmethod "https://api.trello.com/1/members/me/boards?key=$trellokey&token=$global:code"
运行此代码时,您将获得一个登录窗口。登录,然后关闭表格。
登录并单击以授权此 token ,我们需要在以后的代码中使用该 token 。
完成后,您将在控制台中看到它
>we retrieved a code, check within $code for the value
此函数返回
$global:code
全局变量,其中包含您在请求任何信息时需要提供的授权 token 。例如,要查看有关您的用户帐户的信息,最后一行使用/members/me
端点存储有关您的用户帐户的信息。这是完成此请求的方式:$endpoint = "https://api.trello.com/1/members/me/boards"
$auth = "?key=$trellokey&token=$global:code"
$request = $endpoint + $auth
Invoke-RESTMethod $request
现在,您可以使用any of the API endpoints listed in their catalog对Trello进行任何操作。只需将端点替换为所需信息的URL,然后就可以使用。
这是与Web资源进行交互的一种受支持的标准方式,因此您的工作将很有意义。
如果您DID可以使用网页自动化,那么您将受Trello的支配。如果他们更改了他们的页面,则可能必须重写所有代码。
关于powershell - 如何使该PowerShell Web请求正确保存 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38400119/