Skip to content

Instantly share code, notes, and snippets.

@JeremyKennedy
Created November 22, 2021 15:06
Show Gist options
  • Save JeremyKennedy/f337bd13ffd2e7134a6803853f27e951 to your computer and use it in GitHub Desktop.
Save JeremyKennedy/f337bd13ffd2e7134a6803853f27e951 to your computer and use it in GitHub Desktop.
Upload to Nextcloud with PowerShell
# halt script on error
$ErrorActionPreference = "Stop"
# update and print current directory (if using relative path for $file, this will be the base)
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
Write-Output "Source directory: $PWD"
# path of the files to be uploaded
$fileArray = @(
"folder/filename1.csv",
"folder/filename2.csv",
"folder/filename3.csv",
"folder/filename4.csv"
)
# user and pass for webdav access
$user = "USERNAME"
$pass = "PASSWORD"
# url without the last "/"
$destinationPath = "FOLDER/SUBFOLDER/SUBFOLDER"
$baseUrl = "https://HOST_URL/remote.php/dav/files/$user/$destinationPath"
Write-Output "Uploading to Nextcloud directory: $destinationPath "
# set up credentials
$passEncoded = ConvertTo-SecureString -String $pass -AsPlainText -Force
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $passEncoded
# set up SSL
[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
# iterate through list of files to upload
foreach ($file in $fileArray) {
Write-Output "`nProcessing file: $file"
# build url
$fileUrl = $baseUrl + "/" + $file.split('\')[(($file.split("\")).count - 1)]
Write-Output " Using URL: $fileUrl "
# parse file content to upload
Write-Output "` Parsing file..."
$fileContent = ([System.IO.File]::ReadAllBytes($file))
# do upload
Write-Output " Starting upload..."
$response = Invoke-RestMethod -Method Put -Uri $fileUrl -Body $fileContent -Credential $credentials
if ($response -ne "") { Write-Output $response }
Write-Output " Upload complete."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment