I have this script that successfully logs into a website and performs a query:
$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
What I am trying to do is do a similar thing with another website, Trello. This is the script:
$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
However, result variable displays a page as if the user was not logged in, so I'm assuming the session isn't properly saving. How can I fix this?
If you want to work with remote services on the web, the easiest way to do this is by using their API. So here's how to go that route.
Step 1 signup for the API here: https://trello.com/app-key
Copy down this key as your $trelloKey
in the code below.
Step 2 Download this Show-OAuthWindow
function which has been customized to work with Trello.
$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"
When you run this code, you'll get a login window. Sign in and then close the form.
Sign in and and click to authorize this token, which we need to use later in our code.
When this completes, you'll see this in the console
>we retrieved a code, check within $code for the value
This function returns a global variable of $global:code
which contains the authorization token you need to provide when you request any info. For Example, to see information about your user account, the final line stores info about your user account, using the /members/me
endpoint. Here's how this request is done:
$endpoint = "https://api.trello.com/1/members/me/boards"
$auth = "?key=$trellokey&token=$global:code"
$request = $endpoint + $auth
Invoke-RESTMethod $request
You can now use any of the API endpoints listed in their catalog to do whatever you'd like with Trello. Simply replace the endpoint with the URL for the info you want, and away you go.
This is a supported and standard way of interacting with web resources, so your efforts will be well spent.
If you DID get this working with web page automation, you would be at the mercy of Trello. If they made changes to their page, you might have to rewrite all of your code.