PowerShell上传文件到SharePoint子目录下

今天客户有一个需求,需要每天定时产生的报表文件上传SharePoint服务器上,网上找了资料,可以上传到相应的根目录下,就是不能上传到子目录下,测试了很多方法都不行,最后在下班的路上通过手机找到了相关资料,进行了一顿修改后,成功将文件放置到客户SharePoint的指定目录下。
原文连接(英文

如果Windows服务器上没有安装过Sharepoint,那就需要安装一个SharePoint Server 2016 Client Components SDK,安装之后需要确定两个DLL文件的对应位置,在执行PowerShell脚本的时需要用到的,具体可以参考我脚本。

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
#Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
#Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client.Runtime\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.Runtime.dll"

#Specify tenant admin and site URL
$User = "jzh@one.com"
$SiteURL = "https://one.sharepoint.com/sites/Partners/"
$Folder = "D:\username\test\"
$DocLibName = "Documents"
$FolderName = "Analytics"
$Password = "P@ssword"  | ConvertTo-SecureString -AsPlainText -Force

#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)
$Context.Credentials = $Creds

#Retrieve list
$List = $Context.Web.Lists.GetByTitle($DocLibName)
$Context.Load($List.RootFolder)
$Context.ExecuteQuery()

#Retrieve folder
$FolderToBindTo = $List.RootFolder.Folders
$Context.Load($FolderToBindTo)
$Context.ExecuteQuery()
$FolderToUpload = $FolderToBindTo | Where {$_.Name -eq $FolderName}

#Upload file(s)
Foreach ($File in (dir $Folder -File))
{
    $FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
    $FileCreationInfo.Overwrite = $true
    $FileCreationInfo.Content = [System.IO.File]::ReadAllBytes($File.FullName)
    $FileCreationInfo.URL = $List.RootFolder.ServerRelativeUrl + "/" + $FolderName + "/" + $File.Name
    $UploadFile = $List.RootFolder.Files.Add($FileCreationInfo)
    $Context.Load($UploadFile)
    $Context.ExecuteQuery()
}

发表评论

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据