PowerShell Google Drive: Download a File (Stream to the Filesystem)

Back to Index

Downloads the content of a file by ID. (In this example the file id = 1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl) The file is streamed directly to the filesystem. Note: The alt=media query param must be used to download the file content (as opposed to the file metadata).

Documentation: https://developers.google.com/drive/v3/reference/files/get


[Reflection.Assembly]::LoadFile("C:\myAssemblies\ChilkatDotNet2.dll")

$rest = New-Object Chilkat.Rest

#   Provide a previously obtained OAuth2 access token.
$oauth2 = New-Object Chilkat.OAuth2
$oauth2.AccessToken = "OAUTH2_ACCESS_TOKEN"
$rest.SetAuthOAuth2($oauth2)

$success = $rest.Connect("www.googleapis.com",443,$true,$true)
if ($success -ne $true) {
    $($rest.LastErrorText)
    exit
}

$rest.AddQueryParam("includeTeamDriveItems","true")
$rest.AddQueryParam("supportsTeamDrives","true")
$rest.AddQueryParam("alt","media")

#  First send the HTTP request.
$success = $rest.SendReqNoBody("GET","/drive/v3/files/1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl")
if ($success -ne $true) {
    $($rest.LastErrorText)
    exit
}

#  Read the response header.  If the response status code is success, stream to the file.
#  Otherwise receive the error response text.
$statusCode = $rest.ReadResponseHeader()
if ($statusCode -lt 0) {
    $($rest.LastErrorText)
    exit
}

if ($statusCode -ne 200) {
    $("Received error response code: " + $statusCode)
    #  Read the error response body.
    $sbErrResponse = New-Object Chilkat.StringBuilder
    $success = $rest.ReadRespSb($sbErrResponse)
    if ($success -ne $true) {
        $($rest.LastErrorText)
        exit
    }

    $("Error response:" + $sbErrResponse.GetAsString())
    exit
}

#  Stream the response body to the output file.
$respBodyStream = New-Object Chilkat.Stream
$respBodyStream.SinkFile = "/someDirectory/penguins.jpg"
$success = $rest.ReadRespBodyStream($respBodyStream,$true)
if ($success -ne $true) {
    $($rest.LastErrorText)
    exit
}

$("Example Completed.")