Powershell / Google Drive to list files.

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

Parents
No Data
Reply
  • Some sites, just don't allow automation or all the automation you'd like to do. Secondly, you cannot navigate a page without interacting with the UI, aka clicking links or buttons required to move to the next page or subpage. Now, that being said, I don't use G-Drive, so no experience with explicitly what you are doing there. Yet, apparently, the 'Next Page' code is not working. Hence, why you are getting the same stuff all the time.

Children