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.
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.
Thanks for taking the time to comment. I am glad I could help.
This helped me a lot. Thank you Jeffrey!
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.