65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 Powershell 部署 SharePoint 2010

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2投票s)

2011 年 10 月 24 日

CPOL

3分钟阅读

viewsIcon

26501

本文将帮助您使用 Powershell 交付/部署您的 Sharepoint 站点及其功能

引言

本文将通过简单的步骤帮助您打包整个 Sharepoint 2010 站点及其功能,以及如何在客户端环境或不同的测试服务器上交付/部署它们。

使用 Powershell 导出站点

我们将使用 Powershell 文件 (.ps1) 来执行站点的导出操作。 该文件的内容如下所示。 您可以将以下代码复制粘贴到记事本中,将其命名为 Export-Operation.ps1 并将其保存在 Sharepoint 服务器的本地驱动器中。

Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
[System.Reflection.Assembly]::LoadWithPartialName
	("Microsoft.SharePoint.Administration") > $null
[System.Reflection.Assembly]::LoadWithPartialName("System.Collections.Generic") > $null

$currentDir=Convert-Path (Get-Location -PSProvider FileSystem)

$newSiteUrl=$args[0]

function WriteHost ([string] $Msg)
{
	Write-Host $Msg -foregroundcolor yellow
}

$errorActionPreference = 'Inquire'

function ExportSite ([string] $NewSiteUrl)
{	
	$formattedurl=$NewSiteUrl.Replace("http://","")
	$formattedurl=$formattedurl.Replace("/","-")
	$formattedurl=$formattedurl.Replace(":","")
	$path=$currentDir+"\"+$formattedurl+".cmp"

	
	WriteHost " " 
	WriteHost "-------------------------------------------"
	WriteHost "Exporting site",$NewSiteUrl,"- capturing user security..."
	Export-SPWeb -Identity $NewSiteUrl 
		-path $path -Confirm:$false -Force -ErrorVariable errors 
		-IncludeUserSecurity -IncludeVersions All
	if ($errors.Count -eq 0)
	{
    	WriteHost "Export of site",$NewSiteUrl,"complete!"
	}
	
	WriteHost "-------------------------------------------"
	WriteHost " " 
}

if ($args[0] -ne $null)
{
	if(!(test-path logs -pathtype container)){new-item logs -type directory}
	$operationName="export-operation."
	$currentdatetime = get-date -format "yyyy-MM-d.hh-mm-ss"
	$logname=$operationName+$currentdatetime+".log"
	$logfile=$currentDir + "\logs\" + $logname
	Start-Transcript $logfile
	ExportSite $newSiteUrl
	Stop-Transcript
}
else
{
	WriteHost "Invalid arguments supplied"
	WriteHost "Arg 1 = New Site Url"
}

现在我们将使用 Export-Operation.ps1 文件将站点导出到 .cmp 文件。 此操作将站点 URL 作为其参数

步骤 1:在您的 Sharepoint 服务器中打开 Sharepoint 2010 Management Shell,如图所示

步骤 2:在打开的命令提示符中,使用 cd 命令导航到保存文件 Export-Operation.ps1 的路径。

步骤 3:之后执行以下命令

.'[path]/Export-Operation.ps1' [site url] 
eg : .'C:\RiskportalMigratio n2010\PhaseIII\SolutionPackages/Export-Operation.ps1' 
	http://80pd8devsp10:1122 

步骤 4:命令成功执行后,您将在同一位置找到您的包文件 .cmp。 cmp 文件的名称将从您的站点 URL 中获取,您可以很好地重命名它以便更好地理解。 在这里,我们将它重命名为 Riskportal.cmp

现在,我们已成功导出站点。

使用 Powershell 导入站点

在执行此过程之前,我想明确一点,cmp 文件将仅包含站点及其内容,而不包含功能。 我们将使用两个 Powershell 文件 (.ps1) 来执行站点的导入操作。 一个 Import-Operation.ps1 文件用于导入站点,另一个 Deploy-Solutions-InCurrentFolder.ps1 文件用于部署保存在当前文件夹中的所有功能 (.wsp 文件)。 Import-Operation.ps1 文件的内容如下所示。 您可以将以下代码复制粘贴到记事本中,将其命名为 Import-Operation.ps1 并保存它。

Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
[System.Reflection.Assembly]::LoadWithPartialName
		("Microsoft.SharePoint.Administration") > $null
[System.Reflection.Assembly]::LoadWithPartialName("System.Collections.Generic") > $null

$currentDir=Convert-Path (Get-Location -PSProvider FileSystem)

$newSiteUrl=$args[0]
$importFileName=$args[1]
if ($args[2] -eq "-IncludeUserSecurity")
{
$includesecurity=$true
}
else
{
$includesecurity=$false
}

function WriteHost ([string] $Msg)
{
	Write-Host $Msg -foregroundcolor yellow
}

$errorActionPreference = 'Inquire'

function ImportSite ([string] $NewSiteUrl, [string] $ImportFilePath)
{	
	$contentdbweburl="http://"+$urlServerName
	
	WriteHost " " 
	WriteHost "-------------------------------------------"
	if ($includesecurity -eq $true)
	{	
		WriteHost "Importing site",$NewSiteUrl,"- overwriting user security..."
		Import-SPWeb -Identity $NewSiteUrl 
			-path $ImportFilePath -Confirm:$false 
			-Force -ErrorVariable errors -IncludeUserSecurity 
			-UpdateVersions Overwrite
	}
	else
	{
		WriteHost "Importing site",$NewSiteUrl,"
			- user security will not be modified..."
		Import-SPWeb -Identity $NewSiteUrl 
			-path $ImportFilePath -Confirm:$false 
			-Force -ErrorVariable errors -UpdateVersions Overwrite
	}
	if ($errors.Count -eq 0)
	{
    	WriteHost "Import of site",$siteUrl,"complete!"
	}
	
	WriteHost "-------------------------------------------"
	WriteHost " " 
}

if ($args[0] -ne $null -and $args[1] -ne $null)
{
	if(!(test-path logs -pathtype container)){new-item logs -type directory}
	$operationName="import-operation."
	$currentdatetime = get-date -format "yyyy-MM-d.hh-mm-ss"
	$logname=$operationName+$currentdatetime+".log"
	$logfile=$currentDir + "\logs\" + $logname
	Start-Transcript $logfile
	$filePath=$currentDir + "\" + $importFileName
	ImportSite $newSiteUrl $filePath
	Stop-Transcript
}
else
{
	WriteHost "Invalid arguments supplied"
	WriteHost "Arg 1 = New Site Url"
	WriteHost "Arg 2 = Import File Name"
}

Deploy-Solutions-InCurrentFolder.ps1 文件的内容如下所示。 您可以将以下代码复制粘贴到记事本中,将其命名为 Deploy-Solutions-InCurrentFolder.ps1 并保存它。

Add-PsSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
[System.Reflection.Assembly]::LoadWithPartialName
		("Microsoft.SharePoint.Administration") > $null
[System.Reflection.Assembly]::LoadWithPartialName("System.Collections.Generic") > $null

$currentDir=Convert-Path (Get-Location -PSProvider FileSystem)
$operationType = $args[0]
$SiteUrl = $args[1]
$currentdatetime = get-date -format "yyyy-MM-d.hh-mm-ss"
$logname="wsp-deployment."+$currentdatetime+".log"
$wspLogFile=$currentDir + "\" + $logname
$searchPath = $currentDir + "\*.*"

function WriteHost ([string] $Msg)
{
	Write-Host $Msg -foregroundcolor yellow
}

function WaitForJobToFinish([string]$SolutionFileName)
{ 
    $JobName = "*solution-deployment*$SolutionFileName*"
    $job = Get-SPTimerJob | ?{ $_.Name -like $JobName }
    if ($job -eq $null) 
    {
        WriteHost "Timer job not found"
    }
    else
    {
        $JobFullName = $job.Name
        Write-Host -NoNewLine "Waiting to finish job $JobFullName"
        
        while ((Get-SPTimerJob $JobFullName) -ne $null) 
        {
            Write-Host -NoNewLine .
            Start-Sleep -Seconds 2
        }
        Write-Host -NoNewLine  ". Finished waiting for job"
        WriteHost " "
    }
}

function RetractRemoveAdd
{
    param (
        [String]$PackageName,
        [String]$OperationType
    )
# RetractRemoveAdd -PackageName PackageName [-OperationType OperationType]
# OperationType is optional and "update", "deploy", 
	or "redeploy" are the only supported options.
# The default is to "update", unless solution does not exist.

    if (($OperationType -eq $null) -or ($OperationType -eq "")){
	$OperationType = "update"
    } elseif ($OperationType -eq "deploy") {
	$OperationType = "redeploy"
    }
    if (($OperationType -ne "update") -and ($OperationType -ne "redeploy")){
	$OperationType = $null
	WriteHost "Incorrect parameter for OperationType.  
			Use update, deploy, or redeploy"
    }

    WriteHost "Performing",$OperationType,"on",$PackageName    

    $solution = Get-SPSolution | where-object {$_.Name -eq $PackageName}
    # check if solution already deployed
    if (($solution -ne $null) -and ($OperationType -eq "redeploy"))
	{
      Write-Host "Uninstalling previous version of", 
			$PackageName -foregroundcolor yellow
	  
      if ($solution.Deployed -eq $true)
	  {
        if($solution.ContainsWebApplicationResource)
            {
                Uninstall-SPSolution -Identity $PackageName 
			-WebApplication $SiteUrl -Confirm:$false
            }
               else
            {
                Uninstall-SPSolution -Identity $PackageName -Confirm:$false 
            }
			
        while ($Solution.JobExists)
        {
            Start-Sleep 2
        }
		
        WriteHost "SOLUTION HAS BEEN UNINSTALLED SUCCESSFULLY."
      
        Remove-SPSolution -Identity $PackageName -Confirm:$false -Force:$true
		
		$solution = $null
        WriteHost "SOLUTION HAS BEEN REMOVED SUCCESSFULLY."
      }
    }
	
    $SolutionPath=$CurrentDir + "\" + $PackageName
	
    if (($solution -ne $null) -and ($OperationType -eq "update"))
	{
      Write-Host "Updating previous version of", $PackageName -foregroundcolor yellow
      Update-SPSolution -Identity $PackageName -LiteralPath $SolutionPath 
			-GACDeployment -Force:$true -Confirm:$false
      Write-Host "SOLUTION HAS BEEN UPDATED SUCCESSFULLY." -foregroundcolor yellow
     }
	 else
	 {
      Write-Host 'Adding solution:',$SolutionPath -foregroundcolor yellow
      Add-SPSolution -LiteralPath $SolutionPath -Confirm:$false 
      if ($solution -eq $null){ $solution = Get-SPSolution | 
			where-object {$_.Name -eq $PackageName} }
      Write-Host 'Installing solution:',$PackageName -foregroundcolor yellow

      if ($solution.ContainsWebApplicationResource)
      {
          Install-SPSolution -Identity $PackageName -GACDeployment 
		-WebApplication $SiteUrl -Force:$true -Confirm:$false
      }
      else
      {
          Install-SPSolution -Identity $PackageName 
			-GACDeployment -Force:$true -Confirm:$false
      }
      Write-Host "SOLUTION HAS BEEN INSTALLED SUCCESSFULLY." -foregroundcolor yellow
     }
}

function BeginProcessing
{
	Start-Transcript $wspLogFile
	$errorActionPreference = 'Inquire'

	$wspFiles = Get-ChildItem $searchPath -Include *.wsp  

	if ($wspFiles -ne $null)
	{
		$filePathArray = @()
		$fileNameArray = @()
		
		WriteHost ""
		WriteHost "Processing the following file(s) .."
		WriteHost "-----------------------------------------------"
		
		foreach ($wspFile in $wspFiles) 
		{ 
			$fileNameArray = $fileNameArray + $wspFile.Name
			$filePathArray = $filePathArray + $wspFile.FullName	
			WriteHost $wspFile.Name
		}
		
		WriteHost "-----------------------------------------------"
		WriteHost ""
		
		foreach ($fileName in $fileNameArray) 
		{ 
			RetractRemoveAdd -PackageName $fileName 
				-OperationType $operationType
			WriteHost ""
		}
		
		WriteHost ""
		#WriteHost "Restarting IIS .."
		#Restart-Service W3SVC
		#iisreset			
		WriteHost "Operation completed."
			
	}
	else
	{
		WriteHost "Operation skipped. No WSP's found at",$currentDir
	}
	
	Stop-Transcript
}

if ($args[0] -ne $null -and $args[1] -ne $null)
{
	BeginProcessing
}
else
{
	WriteHost "Invalid arguments supplied"
	WriteHost "Arg 1 = Action Directive: [update], [deploy], or [redeploy]"
}

现在我们将创建一个批处理文件 (.cmd) 来按顺序执行此导入操作,以便为安装程序(客户端)简化工作。 您可以将以下代码复制粘贴到记事本中,将其命名为 InstallSite.cmd 并保存它。

@SET TARGETURL=http://80pd8devsp10:1122
@SET PACKAGE=Riskportal.cmp

powershell .\Import-Operation.ps1 %TARGETURL% %PACKAGE%

powershell .\Deploy-Solutions-InCurrentFolder.ps1 redeploy %TARGETURL%

Pause

注意:您必须根据您的目标环境设置您的目标 URL 和包名称并保存它。 现在我们将开始我们的导入操作。

步骤 1:在目标服务器(您将在其中导入站点)中,使用 Sharepoint central admin 创建一个新的 Web 应用程序。

步骤 2:然后为 webapplication 创建一个网站集,在模板选择选项中创建网站集时选择 Custom,然后选择“稍后选择模板”,如图所示

步骤 3:创建站点后,将 powershell 文件 Import-Operation.ps1Deploy-Solutions-InCurrentFolder.ps1InstallSite.cmd 文件保存在目标服务器的同一位置。 然后将站点功能的所有 .wsp 文件以及导出的 .cmp 文件“Riskportal.cmp”也放在同一文件夹中。

步骤 4:一旦所有两个 .ps1 文件、.cmd 文件、.wsp 文件和 .cmp 文件都准备好在同一位置,运行 InstallSite.cmd 以启动导入过程。

步骤 5:如果在安装过程中收到任何警告,请对所有警告选择“是”。

步骤 6:安装完成后,转到新站点以检查您是否成功导入站点及其功能。

解释

命令“powershell .\Import-Operation.ps1 %TARGETURL% %PACKAGE%”会将 .cmp 文件导入到给定的新 URL。

命令“powershell .\Deploy-Solutions-InCurrentFolder.ps1 redeploy %TARGETURL%”将卸载已存在的功能,并将安装同一文件夹中提供的当前版本的 .wsp 文件。

关注点

有时,站点的一些功能在安装期间会失败。 您可以通过执行以下命令重新安装它们

.'[path]/Deploy-Solutions-InCurrentFolder.ps1' redeploy [site url] 

这种部署方法的优势在于,它将简化安装程序的工作。

© . All rights reserved.