I am new in powershell, I need to connect to an API that has OAUTH2.0 authentication, the API generates a file in json format.
If I run the script from POWESHELL ISE it works correctly, it authenticates and downloads a json file
$application = "https://api.xxxx.com/token";
$username = "myuser";
$password = "mypassword";
$creds = @{
username = $username
password = $password
grant_type = "password"
};
$header_token = @{"Content-Type" = "application/x-www-form-urlencoded"}
$header_Out = @{"Accept" = "application/json" ; "authorization" = "bearer $token"}
$datestart = (Get-Date).addDays(-1).tostring(“yyyy-MM-dd”)
$dateend = (Get-Date).addDays(-1).tostring(“yyyy-MM-dd”)
$response = Invoke-RestMethod "$application" -Method Post -Body $creds -Headers $headers;
$token = $response.access_token;
Invoke-WebRequest -Uri "https://api.xxxx.com/api/TrafficData/Hourly?from=$datestart&to=$dateend" -Header $header_Out -OutFile "G:\Traffic.json"
$host.enternestedprompt()
but if i run it from ps1 file it generates authentication error
Error
Anyone know what might be happening?
Thanks for your help
As far as I understand it works on ISE because you develop it inside ISE in the first attempt you give a value to $token
that was kept in the session for the second attempt.
Can you just try to add the line in comment ?
$application = "https://api.xxxx.com/token";
$username = "myuser";
$password = "mypassword";
$creds = @{
username = $username
password = $password
grant_type = "password"
};
$header_token = @{"Content-Type" = "application/x-www-form-urlencoded"}
$header_Out = @{"Accept" = "application/json" ; "authorization" = "bearer $token"}
$datestart = (Get-Date).addDays(-1).tostring(“yyyy-MM-dd”)
$dateend = (Get-Date).addDays(-1).tostring(“yyyy-MM-dd”)
$response = Invoke-RestMethod "$application" -Method Post -Body $creds -Headers $header_token
$token = $response.access_token;
# JPB : Here, you receive the token so you use it
$header_Out = @{"Accept" = "application/json" ; "authorization" = "bearer $token"}
Invoke-WebRequest -Uri "https://api.xxxx.com/api/TrafficData/Hourly?from=$datestart&to=$dateend" -Header $header_Out -OutFile "G:\Traffic.json"
$host.enternestedprompt()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With