Connect to Google API with Powershell

We are going to connect to the Google API with OAuth2.0 and the Powershell Invoke-RestMethod cmdlet. Before we can start scripting in Powershell we first need to get a ClientId, ClientSecret, AuthCode, and finally the Access and Refresh tokens.

It took me half a day to figure out how to connect to where to get what, so I hope you guys (and girls) can get up and running within 10 minutes.

Getting the Google API access and refresh tokens

Go to Google Developers Console and create a new project by clicking on the top bar on API Project and then the + to create a new project. Give your project a name and click Create. When you are done, click again on API Project, click All, and select your newly created project.

You will see the empty dashboard, we need to select which API we want to interact with, I want to get Real-time Analytics data so I selected the Analytics API. Click Enable after which you will be redirected back to the dashboard.

As stated on the dashboard, click on Create Credentials and enter the following:

  • Which API are you using?  > The one you have chosen earlier
  • Where will you be calling the API from? > Webbrowser (Javascript)
  • What data will you be accessing? > User data
  • Authorized redirect URIs > http://localhost/oauth2callback  ! Important
  • Fill in a name for your OAuth 2.0 client ID, does not matter what.
  • Create the OAuth 2.0 consent screen and click done. We will get the credentials from the credentials page.
Google API Powershell

Getting an Authorization code

With the authorization code, we can get access and refresh tokens. We only need these, so I have taken the easy way by just opening the endpoint in the browser, authenticate and crap the code from the address bar.

First, we need the ClientId, so go to the Credential page and copy the clientId. It looks like , paste it in the following URL and open it in your browser:

# Replace <CLIENT_ID_HERE> with your client id<CLIENT_ID_HERE>&scope=

# In the comments below, Phani mentioned that the above url is wrong and should be:<replacemewithclientid>&scope=<replacemewithredirecturi>&access_type=offline&approval_prompt=force

# I have no time to test it, but if you get an error with the original URL, then check the one mentioned by Phani.

Make sure you use the same redirect URLs that we set when we created the credentials. http://localhost/oauth2callback

After you authenticate, you will be redirected to http://localhost/oauth2callback?code=4/QhUXhB*********_***********u8jKZkjhsd2# . Copy the code without the # at the end and store it somewhere, we will need it later.
This code is only one hour valid and if the access token request later fails somehow, you will need to get a new authentication code. So keep that in mind.

Getting access and refresh tokens

To exchange the Authorization code for the tokens, we will use Powershell to make a call to  Fill in the Authorization code, ClienId, Client Secret, and redirect Uri from the Google Developer Console and run the script. It will store the two tokens in the text files so you can use them later on

$requestUri = ""

$body = @{
	grant_type="authorization_code"; # Fixed value

$tokens = Invoke-RestMethod -Uri $requestUri -Method POST -Body $body;

# Store refreshToken
Set-Content $PSScriptRoot"\refreshToken.txt" $tokens.refresh_token

# Store accessToken
Set-Content $PSScriptRoot"\accessToken.txt" $tokens.access_token

Refreshing the access token

The access token is only valid for one hour, so you will need to get a new one with the refresh token. The refresh token from Google does not expire so store it in a secure place. Use the call below to get new access token:

$refreshTokenParams = @{
	grant_type="refresh_token"; # Fixed value

$tokens = Invoke-RestMethod -Uri $requestUri -Method POST -Body $refreshTokenParams

Retrieving data from Google API

So now we have the tokens we can get data from Google. To get started take a look at and

To give you an example, this is how to retrieve the current (real-time) users from Analytics:

# Request URL for Analytics Realtime and requesting the activeUsers
$viewId = 12345678 (Get it from the analytics admin page &gt; view settings)
$requestUri = "$viewId&amp;metrics=rt:activeUsers"

Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $requestUri -Method GET -ContentType 'application/json'

Update: Check this Google API Explorer: It generates an API Query URI for you.

8 thoughts on “Connect to Google API with Powershell”

  1. I was able to get the authorization code, but when I try to get the tokens, I receive the following error:

    Invoke-RestMethod : The remote server returned an error: (400) Bad Request
    At line:1 char:11
    + $tokens = Invoke-RestMethod -Uri $requestUri -Method POST -Body $body …
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

    I tried both versions, from the article and from the comments, does anyone have any idea why I keep receiving bad request?

  2. I was continually getting bad requests using the methods given, including after using the corrected url. The following worked for me to get the access and refresh tokens

    $clientID = “”
    $clientSecret = “”
    $redirectUrl = “”
    $scope = “”

    # Replace with your client id
    $authUrl = “$redirectUrl&client_id=$clientID&scope=$scope&approval_prompt=force&access_type=offline&response_type=code”

    $authUrl | clip
    # Copy the generated url into your browser

    $responseCode = “

    $requestUri = “”

    $body = “code=$([System.Web.HttpUtility]::UrlEncode($responseCode))&redirect_uri=$([System.Web.HttpUtility]::UrlEncode($redirectUrl))&client_id=$clientID&client_secret=$clientSecret&scope=$scope&grant_type=authorization_code”

    $tokens = Invoke-RestMethod -Uri $requestUri -Method POST -Body $body -ContentType “application/x-www-form-urlencoded”

  3. Great, thank you.

    Can you please take the answer from “phani kumar yelisetty” into the document. It take me a long time testing with errors bevor i found it 🙂

  4. I’m in the middle of implementing this guidance. This has clearly shortened my time to follow the instructions @

    One pitfall, that I did hit was that the -requestUri in the “Refreshing the access token” section is NOT the same as in “Getting the access and refresh tokens”. When obtaining the new access token using the refresh token, one must use as the value for -requestUri

  5. hi rudy, thank you for the great article. it sure did help me. but the url mentioned to get the initial code didn’t work for me. what worked was

Leave a Comment