使用 powershell 备份还原 SharePoint 资源

本文介绍了一种使用PowerShell脚本实现SharePoint站点页面的自动化备份与还原的方法。该方法能够过滤并下载aspx页面资源到指定文件夹,同时记录页面信息以便后续上传,并支持页面删除与还原操作。

前几天,应工作需要写了一段用powershell命令将SharePoint站点页面下载备份到本地磁盘,包括:


  1. 过滤aspx页面(可以根据需要过滤想要的资源或不过滤)
  2. 下载页面资源,到指定的文件夹(根据站点和文件夹命名的路径)
  3. 将原来页面信息和下载后的页面信息做一个匹配放到配置文件中方便以后上传,并记录错误日志
  4. 删除(回收)页面
  5. 还原备份的页面


不多说,上代码

备份部分

$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()
}


转载于:https://my.oschina.net/rc6688/blog/161934

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值