Powershell / Google Drive to list files.

by Nov 27, 2019

New to Powershell and never used it to access Google Drive. I'm trying to get powershell to list all of the files / folders in my google drive. I want to use this to check if a folder / file already exists before I upload it. This is all going to be done in the background with no user interaction.

The issue I'm having is the code is getting stuck in the do while loop. It pulls the first page of file names over and over and never goes onto the next page. I have well over 200 files and folders. It keeps spitting out the first 99 over and over until I break it and never displays the $Folders.

Thank you for any help in advance.

$Token="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
$ID="XXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com"
$Secret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"


# Get Access Token
$params = @{
    Uri = 'https://accounts.google.com/o/oauth2/token'
    Body = @(
        "refresh_token=$Token", 
        "client_id=$ID",         
        "client_secret=$Secret", 
        "grant_type=refresh_token"
    ) -join '&'
    Method = 'Post'
    ContentType = 'application/x-www-form-urlencoded'
}
    $accessToken = (Invoke-RestMethod @params).access_token


    $headers = @{
        "Authorization" = "Bearer $($accessToken)"
        "Content-type" = "application/json"
         
    }

    $PSDefaultParameterValues['Invoke-RestMethod:Headers'] = $headers


$files = @()
         $Getparams = @(
         'corpora=user'
         )


    do {        

    $r = (Invoke-RestMethod -Uri "https://www.googleapis.com/drive/v3/files?$($Getparams -join '&')&$nextPage" -Method Get)
    $files += $r.files


    $nextToken = $r.nextPageToken

    if (!$r.files ) {

         $nextPage = $null

       }

       else {
           
        $nextPage = "pageToken=$nextToken"   

       }

      $files.name
   } while ($nextPage)


   $folders = [Array]$files.Where{$_.mimeType -eq 'application/vnd.google-apps.folder'}

   $folders