前几天,应工作需要写了一段用powershell命令将SharePoint站点页面下载备份到本地磁盘,包括:
- 过滤aspx页面(可以根据需要过滤想要的资源或不过滤)
- 下载页面资源,到指定的文件夹(根据站点和文件夹命名的路径)
- 将原来页面信息和下载后的页面信息做一个匹配放到配置文件中方便以后上传,并记录错误日志
- 删除(回收)页面
- 还原备份的页面
不多说,上代码
备份部分
$File = "d:\xxx\backup\url.txt"
$backPath = "d:\xx\backup\"
$errorPath = $backPath+"error.txt"
$importListPath = $backPath+"importList.txt"
$enableBackuo = $true
$enableDelete = $false Write-Host "文件备份:" -NoNewline
if($enableBackuo) {Write-Host "允许" -ForegroundColor green }
else {Write-Host "不允许" -ForegroundColor red}
Write-Host "文件删除:" -NoNewline
if($enableDelete) {Write-Host "允许" -ForegroundColor green}
else {Write-Host "不允许" -ForegroundColor red}
Write-Host ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" -ForegroundColor green
#下载页面的全部信息包含完整的html结构
function WebClientDownload($link, $dir){
$Username = "domain\user"
$Password = "password"
$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password)
$WebClient.DownloadFile( $link, $dir )
}
#下载页面的SharePoint信息,和ribbon菜单中的‘另存为副本’效果一样
function DownLoadPages($file,$dir){
#Downloading file
$binary = $file.OpenBinary()
$stream = New-Object System.IO.FileStream($dir), Create
$writer = New-Object System.IO.BinaryWriter($stream)
$writer.write($binary)
$writer.Close()
}
#正则过滤aspx页面
function GetMatches($link){
$reg = "(?<web>http://[^/]+/.*)Pages(?<dir>.*\/)(?<page>.*)\.aspx?(?<par>.*$)"
if($link -match $reg){
return $Matches
}
return $null
}
Get-Content $File | foreach-Object {
$regResult = GetMatches($_)
$webUrl = $regResult.web
if($regResult -eq $null){
Write-Host "$($_) --> 失败,文件格式不对" -ForegroundColor red
Out-File -FilePath $errorPath -InputObject "$($_) --无法处理" -Append
}
else{
$web = Get-SPWeb $webUrl
$list = $web.lists["页面"]
#设置导出文件的路径
$itemUrl = $regResult.page+".aspx"
$folderUrl = $regResult.dir
$fileUrl = ("pages",$folderUrl,$itemUrl -Join "")
$directory = ($backPath,$web.Title.ToString(),$folderUrl -Join "")
$outFileUrl = ($directory,$itemUrl -Join "\")
$spFolder= $web.GetFolder($list.RootFolder.Url + $folderUrl)
#$Items = $list.Items | where {$_['FileLeafRef'] -eq $itemUrl}
try{
$Items = $spFolder.Files.Item($itemUrl)
if($Items){
#判断目录是否存在
if(!(Test-Path $directory)){
New-Item -ItemType Directory -Path $directory
#new-item -path $backPath -name $web.Title.ToString() -type directory
}
DownLoadPages $web.GetFile($fileUrl) $outFileUrl
Out-File -FilePath $importListPath -InputObject "$($_,$outFileUrl,$folderUrl,$Items.Title -Join ',')" -Append
WebClientDownload $regResult[0] $outFileUrl.Replace(".aspx","_WebClientDownload.aspx")
if($enableDelete){
$Items.Recycle()
}
Write-Host "$($_) --> 成功" -ForegroundColor green
}
else{
Write-Host "$($_) --> 失败,文件不存在" -ForegroundColor red
#如果URL不存在或已删除,则输出提示
Out-File -FilePath $errorPath -InputObject "$($_,'not exist' -Join '--')" -Append
}
}
catch{
Write-Host "$($regResult[0]) --> ERROR" -ForegroundColor red
Out-File -FilePath $errorPath -InputObject "$($_.exception) -- $fileUrl" -Append
}
finally{
$web.dispose()
}
}
}
#去除重复行
$output_importlist = get-content $importListPath | sort | get-unique
Out-File -FilePath $importListPath -InputObject $output_importlist
if((Test-Path $errorPath)){
$output_error = get-content $errorPath | sort | get-unique
Out-File -FilePath $errorPath -InputObject $output_error
}
备份还原部分
#创建文件夹
function CreateFolder($spList, $folderURL)
{
[Microsoft.SharePoint.SPFolder] $spFolder = $web.GetFolder(($list.RootFolder.Url,$folderURL -Join "/"))
if(!$spFolder.Exists)
{
if (!$list.EnableFolderCreation)
{
$list.EnableFolderCreation = true;
$list.Update();
}
$folders = $folderURL.Trim('/').Split('/');
$folderPath =""
foreach ($f in $folders)
{
$folderPath += "/" + $f;
$folder = $list.ParentWeb.GetFolder($list.RootFolder.Url + $folderPath);
if (!$folder.Exists)
{
[Microsoft.SharePoint.SPListItem] $newFolder = $list.Items.Add("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $folderPath.Trim('/'));
$newFolder.Update()
$newFolder["_ModerationStatus"] = 0
$newFolder.Update()
}
}
}
}
#上传文件
function UploadFile($Web, $DocLibName, $FilePath, $folderUrl)
{
$Web.AllowUnsafeUpdates = $true;
$List = $web.Lists[$DocLibName]
$RootFolder = $List.RootFolder
$FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
$File= Get-ChildItem $FilePath
$pageUrl = ( $RootFolder.Url + $folderUrl.TrimEnd("/") +"/"+ $File.Name)
try
{
if(!$Web.GetFile($pageUrl).Exists)
{
[Microsoft.SharePoint.SPFolder] $spFolder = $web.GetFolder( $RootFolder.Url + $folderUrl)
$fileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()
write-host "上传文件 " $File.Name " 到 " $RootFolder.Url + $folderUrl "..."
[Microsoft.SharePoint.SPFile]$spFile = $folder.Files.Add($pageUrl, [System.IO.Stream]$fileStream, $true)
write-host "上传成功" -ForegroundColor green
write-host
$fileStream.Close()
$spFile.Item.Update()
$spFile.CheckIn("")
$spFile.Approve("")
}
}
catch
{
write-host $_.exception -ForegroundColor red
}
finally
{
$Web.AllowUnsafeUpdates = $false;
}
}
$File = "d:\zhangyuepeng\backup\importlist.txt"
Get-Content $File | foreach-Object {
$items = $_.Split(',')
$Url = $items[0]
$regResult = GetMatches($Url)
$webUrl = $regResult.web
$web = Get-SPWeb $webUrl
$list = $web.Lists["页面"]
if($items[2] -ne "/")
{
CreateFolder $list $items[2]
UploadFile $web "页面" $items[1] $items[2] $items[2]
}
else
{
UploadFile $web "页面" $items[1] "" $items[2]
}
$web.dispose()
}