Use PowerShell to get Google Analytics data

I wanted to write a powershell script that will retrieve the number of visits for my site. I put the following script together. Note this uses Google’s ClientLogin for authentication, which is deprecated. I have not worked with OAuth 2 yet.


function JBM-GA-GetStats {
PARAM([string][ValidateSet("CurrentMonth","LastMonth","Today","Yesterday")]$Range="CurrentMonth",
        $GAId="XXXXXXXX",$email="email@company.com",[switch]$MyDebug)

[datetime]$Today=[datetime]::Today
[datetime]$Yesterday=[datetime]::Today.AddDays(-1)
[datetime]$FirstDayCurrentMonth=$Today.AddDays(- ($Today.Day - 1))
[datetime]$FirstDayPreviousMonth=$FirstDayCurrentMonth.AddMonths(-1)
[datetime]$LastDayPreviousMonth=$FirstDayCurrentMonth.AddDays(-1)

switch ($Range){
    "CurrentMonth" {
        $startdate=$FirstDayCurrentMonth.ToString("yyyy-MM-dd")
        $enddate=$Today.ToString("yyyy-MM-dd")
    }
    "LastMonth" {
        $startdate=$FirstDayPreviousMonth.ToString("yyyy-MM-dd")
        $enddate=$LastDayPreviousMonth.ToString("yyyy-MM-dd")        
    }
    "Today" {
        $startdate=$Today.ToString("yyyy-MM-dd")
        $enddate=$Today.ToString("yyyy-MM-dd")   
    }
    "Yesterday"{
        $startdate=$Yesterday.ToString("yyyy-MM-dd")
        $enddate=$Yesterday.ToString("yyyy-MM-dd")   
    }
}

$pw = read-host "Please Enter Your Password" -AsSecureString

$null = [Reflection.Assembly]::LoadWithPartialName("System.Web")   
$password= "Passwd=$([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw)))"

#getting my auth token
$url="https://www.google.com/accounts/ClientLogin?Email=$($email)&$($password)&accountType=GOOGLE&source=mysource&service=analytics"
if ($MyDebug){write-host $url}
$webclient = new-object System.Net.WebClient
$dataString=$webclient.DownloadString($url)
$Auth=$dataString.split("`n")[2].split("=")[1]
if ($MyDebug){write-host $Auth}

#Connecting using auth token to get my data
$webclient.Headers.Add("Authorization", "GoogleLogin auth=$($Auth)")
$url="https://www.google.com/analytics/feeds/data?ids=ga%3A$($GAId)&metrics=ga%3Avisits&start-date=$($startdate)&end-date=$($enddate)&max-results=50"
if ($MyDebug){write-host $url}
$results=$webclient.DownloadString($url)

write-host ("$($Range)'s $($results.feed.entry.metric.name): $($results.feed.entry.metric.value)")
}


One Response to Use PowerShell to get Google Analytics data

  1. Julian January 16, 2014 at 11:27 am #

    First of all Thanks for your nice script. But i can’t run it some how.
    It returns no value? Is it not working because of OAuth2? I tried a different Link but i doest work either. Maybe you can help me

    function JBM-GA-GetStats {
    PARAM([string][ValidateSet(“CurrentMonth”,”LastMonth”,”Today”,”Yesterday”)]$Range=”Today”,
    $GAId=”XXXXXXX”,$email=”XXXXXX”,[switch]$MyDebug)

    [datetime]$Today=[datetime]::Today
    [datetime]$Yesterday=[datetime]::Today.AddDays(-1)
    [datetime]$FirstDayCurrentMonth=$Today.AddDays(- ($Today.Day – 1))
    [datetime]$FirstDayPreviousMonth=$FirstDayCurrentMonth.AddMonths(-1)
    [datetime]$LastDayPreviousMonth=$FirstDayCurrentMonth.AddDays(-1)

    switch ($Range){
    “CurrentMonth” {
    $startdate=$FirstDayCurrentMonth.ToString(“yyyy-MM-dd”)
    $enddate=$Today.ToString(“yyyy-MM-dd”)
    }
    “LastMonth” {
    $startdate=$FirstDayPreviousMonth.ToString(“yyyy-MM-dd”)
    $enddate=$LastDayPreviousMonth.ToString(“yyyy-MM-dd”)
    }
    “Today” {
    $startdate=$Today.ToString(“2013-05-05”)
    $enddate=$Today.ToString(“2013-06-05”)
    }
    “Yesterday”{
    $startdate=$Yesterday.ToString(“2014-01-14”)
    $enddate=$Yesterday.ToString(“2014-MM-dd”)
    }
    }

    $pw = convertto-securestring “XXXXXXXX” -asplaintext -force
    #read-host “Please Enter Your Password” -AsSecureString

    $null = [Reflection.Assembly]::LoadWithPartialName(“System.Web”)
    $password= “Passwd=$([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw)))”

    #getting my auth token
    $url=”https://www.google.com/accounts/ClientLogin?Email=$($email)&$($password)&accountType=GOOGLE&source=mysource&service=analytics”
    if ($MyDebug){write-host $url}
    $webclient = new-object System.Net.WebClient
    $dataString=$webclient.DownloadString($url)
    $Auth=$dataString.split(“`n”)[2].split(“=”)[1]
    if ($MyDebug){write-host $Auth}

    #Connecting using auth token to get my data
    $webclient.Headers.Add(“Authorization”, “GoogleLogin auth=$($Auth)”)
    $url=”https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3AXXXXXXX&start-date=2013-05-05&end-date=2013-06-05&metrics=ga%3Avisits”
    #$url=”https://www.google.com/analytics/v3/data/ga?ids=ga%3A$($GAId)&metrics=ga%3Avisitors&start-date=$($startdate)&end-date=$($enddate)&max-results=50&key={XXXXXXXXXXXXXXXXXXXXXXXX}”
    if ($MyDebug){write-host $url}
    $results=$webclient.DownloadString($url)
    write-host $url
    write-host $result
    write-host $result.feed.value
    write-host $results.feed.entry.metric.name
    write-host $($results.feed.entry.metric.value)
    write-host (“$($Range)’s $($results.feed.entry.metric.name): $($results.feed.entry.metric.value)”)
    }

Powered by WordPress. Designed by WooThemes