Skip to content

Instantly share code, notes, and snippets.

@xrisdoc
Last active August 22, 2019 21:52
Show Gist options
  • Save xrisdoc/a4f8d71a14719ccf2736c22622f9b30e to your computer and use it in GitHub Desktop.
Save xrisdoc/a4f8d71a14719ccf2736c22622f9b30e to your computer and use it in GitHub Desktop.
PowerShell: Upload to Dropbox
Param(
[Parameter(Mandatory=$True)]
[string]$file,
[Parameter(Mandatory=$False)]
[string]$fileNameOverride = "",
[Parameter(Mandatory=$False)]
[boolean]$appendDateTime = $False,
[Parameter(Mandatory=$False)]
[string]$envKey = "DefaultDropboxAccessToken",
[Parameter(Mandatory=$False)]
[string]$token = "",
[Parameter(Mandatory=$False)]
[string]$folderGroup = "",
[Parameter(Mandatory=$False)]
[boolean]$useDatePath = $False
)
# Get the current date/time
# We will use this for filename generartion and directory path where relevant.
$now = [System.DateTime]::Now
# Ensure that no wildcards are specified within the specifed file.
if($file.Contains("*"))
{
Write-Host "Specified source file cannot contain wildcards: $file" -ForegroundColor Red
exit 1
}
# Ensure that the specified source file actually exists
if(-not(Test-Path $file))
{
Write-Host "Specified source file not found: $file" -ForegroundColor Red
exit 1
}
# Ensure that the source file is actually a file.
# This is done by checking that the source file is NOT a directory
if((Get-Item $file) -is [System.IO.DirectoryInfo])
{
Write-Host "Specified source file cannot be a directory: $file" -ForegroundColor Red
exit 1
}
# Obtain the filename from the path.
# This will be the default name for the file when uploading to Dropbox.
# This may end up being overridden.
$fileName = Split-Path $file -leaf
# Check if a value for fileNameOverride has been supplied.
# If it has, then we will use this value as the resulting filename when the file is uploaded to Dropbox.
if($fileNameOverride.Length -gt 0)
{
$fileName = $fileNameOverride
}
# Check if the current date/time is to be appended to the filename
if($appendDateTime -eq $True)
{
$fileDate = $now.ToString("yyyyMMdd-HHmmssfff")
$fileName = $fileDate + "-" +$fileName
}
# Define the default path on Dropbox where the file will be uploaded to
$dropboxPath = "/";
# If a grouping folder has been specified, then append this to the reletive directory
if($folderGroup.Length -gt 0)
{
# Fixup the path
$folderGroup = $folderGroup.Replace("\", "/").Replace("//", "/")
$dropboxPath = $dropboxPath + $folderGroup;
$dropboxPath = $dropboxPath.Replace("\", "/").Replace("//", "/")
}
# Check if the relative directory should contain a date structure.
# If it does, append the relevant date folder to the relative directory.
# This will be useful for organising the backups by date, making it easier to locate the relevant backups.
if($useDatePath -eq $True)
{
$dropboxPath = $dropboxPath + "/" + $now.ToString("yyyy") + "/" + $now.ToString("MM-MMMM") + "/" + $now.ToString("dd-dddd")
}
# Combine the dropbox path and filename
# This is the path to where the file will be uploaded to within Dropbox.
$dropboxFileLocation = $dropboxPath + "/" + $fileName
$dropboxFileLocation = $dropboxFileLocation.Replace("\", "/").Replace("//", "/")
# Output the information
""
"---------------------------------------------"
"Attempting to upload the specified to Dropbox"
"---------------------------------------------"
""
"File Source : $file"
"Filename Override : $fileNameOverride"
"Append Date? : $appendDateTime"
"Use Date Path? : $useDatePath"
"Folder Group : $folderGroup"
"Dropbox Path : $dropboxPath"
"Dropbox Save Path : $dropboxFileLocation"
""
"---------------------------------------------"
""
# NOTE:
# Dropbox integration is with an App Folder
# This means that we will only be able to work with a single dropbox folder
# NOTE:
# You will need to add an Environment variable named DefaultDropboxAccessToken and set the value to the relevant Dropbox Access Token
# Otherwise, the Dropbox Access Token can be overridden by supplying the token through the "-token" parameter
$dboxApiAccessToken = ""
if($token.Length -gt 0)
{
$dboxApiAccessToken = $token
Write-Host "Using override value for Dropbox Access Token" -ForegroundColor "yellow"
}
else
{
# Attempt to retrieve the token from the specified Environment Variable.
if(-not(Test-Path "env:$envKey"))
{
Write-Host "ERROR: Could not obtain Environment Variable for Dropbox Access Token [$envKey]" -foregroundcolor Red
exit 1
}
$dboxApiAccessToken = (get-item "env:$envKey").Value
Write-Host "Using Environment Variable for Dropbox Access Token: $envKey" -ForegroundColor "yellow"
}
# Check if a valid access tocken has been obtained.
# We cannot proceed with the upload unless we have this token.
if($dboxApiAccessToken.Length -gt 0)
{
Write-Host "Starting Upload to Dropbox" -foregroundcolor Yellow
# Specify the URL Resource where the file is to be POSTed to
$dropboxRestEndpoint = "https://content.dropboxapi.com/2/files/upload"
$arg = '{ "path": "' + $dropboxFileLocation + '", "mode": "add", "autorename": true, "mute": false }'
$authorization = "Bearer " + $dboxApiAccessToken
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", $authorization)
$headers.Add("Dropbox-API-Arg", $arg)
$headers.Add("Content-Type", 'application/octet-stream')
try {
Invoke-RestMethod -Uri $dropboxRestEndpoint -Method Post -InFile $file -Headers $headers
Write-Host "Dropbox Upload Complete" -foregroundcolor Green
}
catch {
$dboxErrorMessage = $_.Exception.Message
Write-Host "File not uploaded to dropbox" -foregroundcolor Red
Write-Host "ERROR: $dboxErrorMessage" -foregroundcolor Red
exit 1
}
}
else
{
Write-Host "ERROR: No valid dropbox access token" -foregroundcolor Red
exit 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment