Solution
For our use case, we have a drop location where our files are located. We need to read all the files and upload them to a SharePoint document library.
Note: We can run this snippet using Visual Studio Code. Just save the file with an extension of ps1, and VS Code will guide you on installing the PowerShell extensions.
# include the web cmdlets
Add-PSSnapin microsoft.sharepoint.powershell
# name: uploadFiles
# purpose: upload multiple files from a shared location
#
function uploadFiles($path, $siteUrl)
{
try {
# gets all the files (-File) in the directory
$files = Get-ChildItem -Path $path –File
#iterate thru each file
foreach($file in $files)
{
$url = $siteUrl + $file
$filePath = $path + $file
#upload the file to the server using default credentials from the
#current session
$result = Invoke-WebRequest -Uri $url -InFile $filePath -Method PUT
-UseDefaultCredentials
#if the request status code is successful, we delete the files
#else write an error message
if($result.statuscode -eq 200){
Remove-Item $filePath -Force
}else{
write-host "Failed to upload" $filePath $result.statuscode
}
}
}
catch {
write-host "Exception was raised: $PSItem" #psitem is the error object
}
}
#usage
#uploadFiles parm0 param1
#param[0] shared-location
#param[1] sharepoint document library url
#
UploadFiles "\\some-document-path" "https://ozkary.com/shared-docs/"
In this snippet, we first need to include the snap-in for SharePoint. This loads the web cmdlets that provide the implementation abstraction to the SharePoint APIs.
The uploadFiles function enables us to read a folder location and lists only the files. We then iterate thru each file and use the Invoke-WebRequest to load them to a particular SharePoint document library. If the response has Status 200, we know that the upload was a success, and we remove the file. Otherwise, we write to the standard output using write-host.
Security
We should notice that when uploading the files, we use the -DefaultCredentials parameter. This enables our script to pass the current session credentials to the request. The credentials are set when the script is executed under the context of a particular service account that has access to the SharePoint document library.
I hope this provides a quick automated way to upload files to your document libraries.
0 comments :
Post a Comment
What do you think?