简体   繁体   中英

How to use Invoke-Webrequest to download Salesforce report

I need to download a Salesforce report, previously I have been doing some manual work by clicking buttons, I recently found out that I can just add a few parameters at the end of the url to have chrome download it without clicking export

# Link to the report
https://mycompanydomain.com/00O3md123456789qf 
# when I add these to the end of the link and paste it to chrome, chrome will download directly
https://mycompanydomain.com/00O3md123456789qf?export=1&enc=UTF-8&xf=csv

Is there a way to automate it with Powershell? I tried to use Invoke Webrequest but it does not work the way I wanted, it does not download the actual file but returns the response status.

# get Salesforce Data
$url = "https://mycompanydomain.com/00O3md123456789qf?export=1&enc=UTF-8&xf=csv"
$output =  ".\salesforce.csv"
$start_time = Get-Date
Invoke-WebRequest -Uri $url -OutFile $output
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

I can't help you with PowerShell but Salesforce's REST API contains lots of examples using cURL library. You might be able to adapt something from them or maybe there are cool blog posts like https://www.jbmurphy.com/2016/07/25/connecting-to-the-salesforce-rest-api-using-powershell/ . Here's a cURL login call in documentation

curl https://login.salesforce.com/services/oauth2/token -d "grant_type=password" -d 
"client_id=myclientid" -d "client_secret=myclientsecret" 
-d "username=mylogin@salesforce.com" -d "password=mypassword123456"

You can make raw requests manually or write a small program in Java/C#/Python/PHP using one of ready SF connection libraries.

Basically you need to make 2 calls

  1. one POST to log in and obtain session id
  2. one GET to pull the report. It must include a header with the session id. As you're mimicking a normal user accessing web version of SF - the header must pretend to be Cookie sid=sessionidgoeshere . If you'd use proper API calls (yes, there is a reporting API good for exporting, modifying reports and doing many cool things) you'd use Authorization Bearer sessionidgoeshere

SO yeah, that should give you enough info to start googling "powershell login to salesforce" kind of thing if all you're after is a solution. If you want to understand bit more read on

I've answered few similar questions, please check

If you've never done an OAuth2 flow before (at first reading there are lots of options and the easiest "username password" flow is bit hidden on the giant intimidating list ) it might help if you start by just clicking through https://openidconnect.herokuapp.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM