PowerShell: Retrieving a Salesforce Authentication Token

I’ve recently been working on a new starters creation process. The process relied heavily on querying a hosted HR system on Salesforce. To achieve this a Salesforce authentication token was required to invoke rest methods via PowerShell.

Using PowerShell I was able to create the below function to achieve this :).

PowerShell Function


Function Get-SalesforceAuthToken{
[CmdletBinding()]
param($ClientID,$URL = 'https://login.salesforce.com/services/oauth2/token',$clientSecret,$username,$password)

try {
$result = Invoke-RestMethod $URL `
-Method Post `
-Body @{
grant_type = "password"
client_id = "$ClientID"
client_secret = "$clientSecret"
username = "$username"
password = "$password"
}

Return $result
}
Catch
{
$ErrorMessage = $_.Exception.Message
Write-Verbose -Message $ErrorMessage
Throw "Error $ErrorMessage"
}
}

Calling The PowerShell Function


$Authcode = (Get-FairsailAuthToken -ClientID $client -clientSecret $secret -username $user -password $pass)
$Authcode

Using the Authenication Token


$query = "<query>"
$APIresult = Invoke-RestMethod "$($Authcode.instance_url)/services/data/v28.0/query?q=$query" `
-Method Get `
-Headers @{
Authorization = "Bearer $($Authcode.Access_Token)"
Accept = "application/xml"
}

Tagged with:

Leave a Reply

Your email address will not be published. Required fields are marked *