Forum Discussion
Ankit007
Dec 09, 2020Copper Contributor
Uploading folders in sharepoint from powershell
My below code successfully read a folder and uploades the subfolder one by one as a zip file in SharePoint. But if any of my file is of Zip extension, it gives me an error. I would like to know how c...
tumtum1973
Jan 10, 2021Copper Contributor
You could modify the UPLOAD-FILE function to skip files with a .zip extension and assign them to the $file value for upload.
# upload the file
Function UPLOAD-FILE
{
param($workingDir, $tempDir, $clientId, $clientSecret, $artifactname)
Get-ChildItem $workingDir | ForEach-Object {
$name = $_.FullName.Split("\")[-1]
if ($name -contains ".zip") {
#skip file
$file = $_.FullName + "\" +$tempDir + "\" + "$($name)"
}
else {
CREATE-ARCHIVE -workingDir $_.FullName -tempDir $tempDir -name $name
$file = $_.FullName + "\" +$tempDir + "\" + "$($name).zip"
}
$fileSize = (Get-Item $file).length
$uploadURLObject = GET-UPLOADLINK -clientId $clientId -clientSecret $clientSecret -artifactname $name
$tokenObject = GET-TOKEN -clientId $clientId -clientSecret $clientSecret
$uploadHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$uploadHeaders.Add("Content-Type", "application/json")
$uploadHeaders.Add("Content-Range", "bytes " + 0 +"-" + ($fileSize-1) + "/" + $fileSize)
$uploadHeaders.Add("Content-Length", $fileSize)
$uploadHeaders.Add("Authorization", "Bearer "+ $tokenObject.access_token)
$uploadBody = [System.IO.File]::ReadAllBytes($file)
$response = Invoke-RestMethod $uploadURLObject.uploadUrl -Method 'PUT' -Headers $uploadHeaders -Body $uploadBody
$response | ConvertTo-Json
REMOVE-TEMPDIR -workingDir $_.FullName -tempDir $tempDirectory
}
}