Connecting to the Salesforce REST api using PowerShell

As I said in my previous post, we are starting to use Salesforce, and I like REST APIs, so I wanted to see how to connect to Salesforce with cuRL and PowerShell.

cURL was pretty easy, PowerShell was not so much. The biggest issue was that when I queried the standard “https://login.salesforce.com/services/oauth2/token” url, I would get one response back, but if I tried again, it wouldn’t work. I had to install fiddler to figure out what was going on. I finally found the error and this solution: use your instance ID in the URL. That took me half a day to figure out. Add-on a typo of not having https in the URL, and I was not having fun. Once I figured out that you need to use your instance url and https I hit this error:

salesforce stronger security is required

So I had to figure out how to force Invoke-WebRequest or Invoke-RestMethod to use TLS 1.2. Here is the code that I finnanly figred out that gets an access token and queries accounts.


[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$tokenurl = "https://InstanceName-dev-ed.my.salesforce.com/services/oauth2/token"
$postParams = [ordered]@{
grant_type="password";
client_id="ReallyLongClientIDReallyLongClientIDReallyLongClientIDReallyLongClientIDReallyLongCli";
client_secret="1234567890123456789";
username="[email protected]";
password="PasswordAndTokenNoSpaces";
}

$access_token=(Invoke-RestMethod -Uri $tokenurl -Method POST -Body $postParams).access_token

$url = "https://InstanceName-dev-ed.my.salesforce.com/services/data/v37.0/sobjects/Account"
Invoke-RestMethod -Uri $url -Headers @{Authorization = "Bearer " + $access_token}


you don’t need the [ordered] part of the hash table, i was just using it to troubleshoot.

4 Responses to Connecting to the Salesforce REST api using PowerShell

  1. Josiah Denny August 17, 2016 at 1:12 pm #

    I came across this after hours of trying to get it to work. I spent way too much time comparing requests in Fiddler that I made from both Powershell and Postman (Postman was successful every time.) I added [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 to my script and it started working. Thanks SO much for posting this.

  2. jbmurphy August 17, 2016 at 2:09 pm #

    Thanks for taking the time to comment. I am glad I could help.

  3. Pasi December 31, 2016 at 5:43 am #

    This helped me a lot. Thank you Jeffrey!

  4. Vipin April 7, 2017 at 8:02 pm #

    Thank you SO much for posting this, the trick was to use [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

    I can, in fact, access it without instance name in the URL. Since I want to fetch the instance name dynamically, it helps.

Leave a Reply

Powered by WordPress. Designed by WooThemes