プログラムを使用してコンテンツをバックアップする
最終更新日: 2010年11月4日
適用対象: SharePoint Foundation 2010
ここでは、SharePoint Foundation コンテンツ コンポーネントのバックアップをプログラムする方法について説明します。このトピックでは、「SharePoint Foundation でのデータのバックアップと復元の概要」および「SharePoint Foundation のバックアップ/復元オブジェクト モデルを使用したプログラミング」の内容を理解していることを前提としています。
コンテンツ コンポーネントをバックアップするには
Microsoft.SharePoint への参照を Visual Studio に追加し、Microsoft.SharePoint.Administration 名前空間と Microsoft.SharePoint.Administration.Backup 名前空間の using ステートメントをコード ファイルに追加します。
Main メソッド内で、バックアップを格納する場所を指定するようにユーザーに要求します。
Console.Write("Enter full UNC path to the directory where the backup will be stored:"); String backupLocation = Console.ReadLine();
Console.Write("Enter full UNC path to the directory where the backup will be stored:") Dim backupLocation As String = Console.ReadLine()
Main メソッド内で、静的な GetBackupSettings メソッドを使用して SPBackupSettings オブジェクトを作成します。1 つ目のパラメータでは、バックアップの格納先のパスを渡します。2 つ目のパラメータでは、SPBackupMethodType のいずれかの値の文字列バージョンを渡します。
SPBackupSettings settings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full");
Dim settings As SPBackupSettings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full")
バックアップするコンテンツ コンポーネントを指定するようにユーザーに要求し、その名前を IndividualItem プロパティに割り当てます。前回の完全バックアップに含まれていた、バックアップ操作の対象にできるファーム内のコンポーネントの名前のリストを表示するには、サーバー コマンド ラインで stsadm -o backup -showtree コマンドを実行するか、サーバーの全体管理アプリケーションで [サーバー構成の管理] から [バックアップの実行] にアクセスします。ファーム全体を指定するには、名前で "Farm" を使用します (プロパティを null に設定した場合も、バックアップのファーム全体が選択されます。ただし、以降のすべてのコードで、バックアップするコンポーネントを IndividualItem を使用して名前で識別することが前提になります。例については、手順 8. の FindItems() メソッドの使用方法を参照してください)。
Console.Write("Enter name of component to backup (default is whole farm):"); settings.IndividualItem = Console.ReadLine();
Console.Write("Enter name of component to backup (default is whole farm):") settings.IndividualItem = Console.ReadLine()
必要に応じて、IsVerbose プロパティ、UpdateProgress プロパティ、および BackupTheads() プロパティのいずれかまたは複数を設定します (これらのプロパティの詳細については、それぞれのリファレンス トピックを参照してください)。
settings.IsVerbose = true; settings.UpdateProgress = 10; settings.BackupThreads = 2;
settings.IsVerbose = True settings.UpdateProgress = 10 settings.BackupThreads = 2
CreateBackupRestore() メソッドを使用してバックアップ操作を作成します (操作の履歴オブジェクトも作成されます。詳細については、「SPBackupRestoreHistoryObject」および「SPBackupRestoreHistoryList」を参照してください)。
Guid backup = SPBackupRestoreConsole.CreateBackupRestore(settings);
Dim backup As Guid = SPBackupRestoreConsole.CreateBackupRestore(settings)
UI でユーザーにコンポーネント名をリストから選択させるのではなく入力させる場合は、入力された名前がいずれかのコンポーネントと正確に一致することを確認する必要があります。Main メソッドに次の行を追加します。
SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref backup);
Dim node As SPBackupRestoreObject = EnsureUniqueValidComponentName(settings, backup)
以下の EnsureUniqueValidComponentName メソッドの実装を追加します。FindItems() メソッドを使用して、ユーザーが入力した名前と名前が一致するコンテンツ オブジェクトのコレクションを取得します。一致する名前がない場合は、再度実行するようにユーザーに要求します。一致する名前が複数ある場合は、いずれかを指定するようにユーザーに要求します。ユーザーが入力したコンポーネント名が有効で特定できた場合は、ユーザーが復元するコンポーネントを表す SPBackupRestoreObject オブジェクトへの参照を取得します。
private static SPBackupRestoreObject EnsureUniqueValidComponentName(SPBackupRestoreSettings settings, ref Guid operationGUID) { SPBackupRestoreObjectCollection list = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem); SPBackupRestoreObject component = null; if (list.Count <= 0) { Console.WriteLine("There is no component with that name. Run again with a new name."); Console.WriteLine("Press Enter to continue."); Console.ReadLine(); } else if (list.Count > 1) // The component name specified is ambiguous. Prompt user to be more specific. { Console.WriteLine("More than one component matches the name you entered."); Console.WriteLine("Run again with one of the following:"); for (int i = 0; i < list.Count; i++) { Console.WriteLine("\t{0}", list[i].ToString()); } Console.WriteLine("Press Enter to continue."); Console.ReadLine(); } else { component = list[0]; } return component; }
Private Shared Function EnsureUniqueValidComponentName(ByVal settings As SPBackupRestoreSettings, ByRef operationGUID As Guid) As SPBackupRestoreObject Dim list As SPBackupRestoreObjectCollection = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem) Dim component As SPBackupRestoreObject = Nothing If list.Count <= 0 Then Console.WriteLine("There is no component with that name. Run again with a new name.") Console.WriteLine("Press Enter to continue.") Console.ReadLine() ElseIf list.Count > 1 Then ' The component name specified is ambiguous. Prompt user to be more specific. Console.WriteLine("More than one component matches the name you entered.") Console.WriteLine("Run again with one of the following:") For i As Integer = 0 To list.Count - 1 Console.WriteLine(vbTab & "{0}", list(i).ToString()) Next i Console.WriteLine("Press Enter to continue.") Console.ReadLine() Else component = list(0) End If Return component End Function
Main メソッドで、バックアップのための十分な容量があるかどうかを示す Boolean フラグと、EnsureUniqueValidComponentName メソッドが有効なノードを返した場合にのみ実行される条件構造を作成します。
Boolean targetHasEnoughSpace = false; if (node != null) { targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node); }
Dim targetHasEnoughSpace As Boolean = False If node IsNot Nothing Then targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node) End If
以下の EnsureEnoughDiskSpace メソッドの実装を追加します。DiskSizeRequired() メソッドを使用して必要な容量を取得し、DiskSize() メソッドを使用してバックアップ先のディスクで使用できる空き容量を確認します。
private static Boolean EnsureEnoughDiskSpace(String location, Guid backup, SPBackupRestoreObject node) { UInt64 backupSize = SPBackupRestoreConsole.DiskSizeRequired(backup, node); UInt64 diskFreeSize = 0; UInt64 diskSize = 0; Boolean hasEnoughSpace = true; try { SPBackupRestoreConsole.DiskSize(location, out diskFreeSize, out diskSize); } catch { diskFreeSize = diskSize = UInt64.MaxValue; } if (backupSize > diskFreeSize) { // Report through your UI that there is not enough disk space. Console.WriteLine("{0} bytes of space is needed but the disk hosting {1} has only {2}.", backupSize, location, diskFreeSize); Console.WriteLine("Please try again with a different backup location or a smaller component."); hasEnoughSpace = false; } else if (backupSize == UInt64.MaxValue || diskFreeSize == 0) { // Report through your UI that it cannot be determined whether there is enough disk space. Console.WriteLine("Cannot determine if that location has enough disk space."); Console.WriteLine("Please try again with a different backup location or a smaller component."); hasEnoughSpace = false; } return hasEnoughSpace; }
Private Shared Function EnsureEnoughDiskSpace(ByVal location As String, ByVal backup As Guid, ByVal node As SPBackupRestoreObject) As Boolean Dim backupSize As UInt64 = SPBackupRestoreConsole.DiskSizeRequired(backup, node) Dim diskFreeSize As UInt64 = 0 Dim diskSize As UInt64 = 0 Dim hasEnoughSpace As Boolean = True Try SPBackupRestoreConsole.DiskSize(location, diskFreeSize, diskSize) Catch diskSize = UInt64.MaxValue diskFreeSize = diskSize End Try If backupSize > diskFreeSize Then ' Report through your UI that there is not enough disk space. Console.WriteLine("{0} bytes of space is needed but the disk hosting {1} has only {2}.", backupSize, location, diskFreeSize) Console.WriteLine("Please try again with a different backup location or a smaller component.") hasEnoughSpace = False ElseIf backupSize = UInt64.MaxValue OrElse diskFreeSize = 0 Then ' Report through your UI that it cannot be determined whether there is enough disk space. Console.WriteLine("Cannot determine if that location has enough disk space.") Console.WriteLine("Please try again with a different backup location or a smaller component.") hasEnoughSpace = False End If Return hasEnoughSpace End Function
Main メソッドで、EnsureEnoughDiskSpace メソッドが true を返した場合にのみ実行される条件構造を作成します。
if (targetHasEnoughSpace) { // TODO: Set the backup operation as the active operation // and run it. }
If targetHasEnoughSpace Then ' TODO: Set the backup operation as the active operation ' and run it. End If
前の手順の "TODO" 行を次のコードに置き換えます。これにより、操作が SetActive() メソッドによってアクティブな操作として設定され、操作が成功するかどうかを確認するためにテストが実行されます。別のバックアップ操作または復元操作が既に実行中である場合など、操作に失敗した場合は、アプリケーションの UI でエラーを報告します。
if (SPBackupRestoreConsole.SetActive(backup) == true) { // TODO: Run the operation. See next step. } else { // Report through your UI that another backup // or restore operation is underway. Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends."); }
If SPBackupRestoreConsole.SetActive(backup) = True Then ' TODO: Run the operation. See next step. Else ' Report through your UI that another backup ' or restore operation is underway. Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends.") End If
SetActive() 呼び出しが成功した場合に実行されるコード分岐で、Run() メソッドを使用して操作を実行します。操作が成功するかどうかをテストします。失敗した場合、操作が失敗したことを示すメッセージを UI で報告します。前の手順の "TODO" 行を次のコードに置き換えます。
if (SPBackupRestoreConsole.Run(backup, node) == false) { // Report "error" through your UI. String error = SPBackupRestoreConsole.Get(backup).FailureMessage; Console.WriteLine(error); }
If SPBackupRestoreConsole.Run(backup, node) = False Then ' Report "error" through your UI. Dim [error] As String = SPBackupRestoreConsole.Get(backup).FailureMessage Console.WriteLine([error]) End If
Remove() メソッドを使用して復元をクリーンアップします。手順 11. で挿入した閉じかっこの直前に以下のコードを追加します。
// Clean up the operation. SPBackupRestoreConsole.Remove(backup); Console.WriteLine("Backup attempt complete. Press Enter to continue."); Console.ReadLine();
' Clean up the operation. SPBackupRestoreConsole.Remove(backup) Console.WriteLine("Backup attempt complete. Press Enter to continue.") Console.ReadLine()
例
次のコードは、コンテンツ コンポーネントのバックアップのプログラミング方法を示しています。
using System;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Backup;
namespace MyCompany.SharePoint.Administration.Backup
{
class Backup
{
static void Main(string[] args)
{
// Identify the location for the backup storage.
Console.Write("Enter full UNC path to the directory where the backup will be stored:");
String backupLocation = Console.ReadLine();
// Create the backup settings.
SPBackupSettings settings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full");
// Identify the content component to backup.
Console.Write("Enter name of component to backup (default is whole farm):");
settings.IndividualItem = Console.ReadLine();
// Set optional operation parameters.
settings.IsVerbose = true;
settings.UpdateProgress = 10;
settings.BackupThreads = 10;
// Create the backup operation and return its ID.
Guid backup = SPBackupRestoreConsole.CreateBackupRestore(settings);
// Ensure that user has identified a valid and unique component.
SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref backup);
// Ensure that there is enough space.
Boolean targetHasEnoughSpace = false;
if (node != null)
{
targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node);
}
// If there is enough space, attempt to run the backup.
if (targetHasEnoughSpace)
{
// Set the backup as the active job and run it.
if (SPBackupRestoreConsole.SetActive(backup) == true)
{
if (SPBackupRestoreConsole.Run(backup, node) == false)
{
// Report "error" through your UI.
String error = SPBackupRestoreConsole.Get(backup).FailureMessage;
Console.WriteLine(error);
}
}
else
{
// Report through your UI that another backup
// or restore operation is underway.
Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends.");
}
// Clean up the operation.
SPBackupRestoreConsole.Remove(backup);
Console.WriteLine("Backup attempt complete. Press Enter to continue.");
Console.ReadLine();
}
}// end Main
private static SPBackupRestoreObject EnsureUniqueValidComponentName(SPBackupRestoreSettings settings, ref Guid operationGUID)
{
SPBackupRestoreObjectCollection list = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem);
SPBackupRestoreObject component = null;
if (list.Count <= 0)
{
Console.WriteLine("There is no component with that name. Run again with a new name.");
Console.WriteLine("Press Enter to continue.");
Console.ReadLine();
}
else if (list.Count > 1) // The component name specified is ambiguous. Prompt user to be more specific.
{
Console.WriteLine("More than one component matches the name you entered.");
Console.WriteLine("Run again with one of the following:");
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine("\t{0}", list[i].ToString());
}
Console.WriteLine("Press Enter to continue.");
Console.ReadLine();
}
else
{
component = list[0];
}
return component;
}// end EnsureUniqueValidComponentName
private static Boolean EnsureEnoughDiskSpace(String location, Guid backup, SPBackupRestoreObject node)
{
UInt64 backupSize = SPBackupRestoreConsole.DiskSizeRequired(backup, node);
UInt64 diskFreeSize = 0;
UInt64 diskSize = 0;
Boolean hasEnoughSpace = true;
try
{
SPBackupRestoreConsole.DiskSize(location, out diskFreeSize, out diskSize);
}
catch
{
diskFreeSize = diskSize = UInt64.MaxValue;
}
if (backupSize > diskFreeSize)
{
// Report through your UI that there is not enough disk space.
Console.WriteLine("{0} bytes of space is needed but the disk hosting {1} has only {2}.", backupSize, location, diskFreeSize);
Console.WriteLine("Please try again with a different backup location or a smaller component.");
hasEnoughSpace = false;
}
else if (backupSize == UInt64.MaxValue || diskFreeSize == 0)
{
// Report through your UI that it cannot be determined whether there is enough disk space.
Console.WriteLine("Cannot determine if that location has enough disk space.");
Console.WriteLine("Please try again with a different backup location or a smaller component.");
hasEnoughSpace = false;
}
return hasEnoughSpace;
}// end EnsureEnoughDiskSpace
}// end Backup class
}// end namespace
Imports System
Imports Microsoft.SharePoint.Administration
Imports Microsoft.SharePoint.Administration.Backup
Namespace MyCompany.SharePoint.Administration.Backup
Module Backup
Sub Main(ByVal args() As String)
' Identify the location for the backup storage.
Console.Write("Enter full UNC path to the directory where the backup will be stored:")
Dim backupLocation As String = Console.ReadLine()
' Create the backup settings.
Dim settings As SPBackupSettings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full")
' Identify the content component to backup.
Console.Write("Enter name of component to backup (default is whole farm):")
settings.IndividualItem = Console.ReadLine()
' Set optional operation parameters.
settings.IsVerbose = True
settings.UpdateProgress = 10
settings.BackupThreads = 10
' Create the backup operation and return its ID.
Dim backup As Guid = SPBackupRestoreConsole.CreateBackupRestore(settings)
' Ensure that user has identified a valid and unique component.
Dim node As SPBackupRestoreObject = EnsureUniqueValidComponentName(settings, backup)
' Ensure that there is enough space.
Dim targetHasEnoughSpace As Boolean = False
If node IsNot Nothing Then
targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node)
End If
' If there is enough space, attempt to run the backup.
If targetHasEnoughSpace Then
' Set the backup as the active job and run it.
If SPBackupRestoreConsole.SetActive(backup) = True Then
If SPBackupRestoreConsole.Run(backup, node) = False Then
' Report "error" through your UI.
Dim [error] As String = SPBackupRestoreConsole.Get(backup).FailureMessage
Console.WriteLine([error])
End If
Else
' Report through your UI that another backup
' or restore operation is underway.
Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends.")
End If
' Clean up the operation.
SPBackupRestoreConsole.Remove(backup)
Console.WriteLine("Backup attempt complete. Press Enter to continue.")
Console.ReadLine()
End If
End Sub ' end Main
Private Function EnsureUniqueValidComponentName(ByVal settings As SPBackupRestoreSettings, ByRef operationGUID As Guid) As SPBackupRestoreObject
Dim list As SPBackupRestoreObjectCollection = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem)
Dim component As SPBackupRestoreObject = Nothing
If list.Count <= 0 Then
Console.WriteLine("There is no component with that name. Run again with a new name.")
Console.WriteLine("Press Enter to continue.")
Console.ReadLine()
ElseIf list.Count > 1 Then ' The component name specified is ambiguous. Prompt user to be more specific.
Console.WriteLine("More than one component matches the name you entered.")
Console.WriteLine("Run again with one of the following:")
For i As Integer = 0 To list.Count - 1
Console.WriteLine(vbTab & "{0}", list(i).ToString())
Next i
Console.WriteLine("Press Enter to continue.")
Console.ReadLine()
Else
component = list(0)
End If
Return component
End Function ' end EnsureUniqueValidComponentName
Private Function EnsureEnoughDiskSpace(ByVal location As String, ByVal backup As Guid, ByVal node As SPBackupRestoreObject) As Boolean
Dim backupSize As UInt64 = SPBackupRestoreConsole.DiskSizeRequired(backup, node)
Dim diskFreeSize As UInt64 = 0
Dim diskSize As UInt64 = 0
Dim hasEnoughSpace As Boolean = True
Try
SPBackupRestoreConsole.DiskSize(location, diskFreeSize, diskSize)
Catch
diskSize = UInt64.MaxValue
diskFreeSize = diskSize
End Try
If backupSize > diskFreeSize Then
' Report through your UI that there is not enough disk space.
Console.WriteLine("{0} bytes of space is needed but the disk hosting {1} has only {2}.", backupSize, location, diskFreeSize)
Console.WriteLine("Please try again with a different backup location or a smaller component.")
hasEnoughSpace = False
ElseIf backupSize = UInt64.MaxValue OrElse diskFreeSize = 0 Then
' Report through your UI that it cannot be determined whether there is enough disk space.
Console.WriteLine("Cannot determine if that location has enough disk space.")
Console.WriteLine("Please try again with a different backup location or a smaller component.")
hasEnoughSpace = False
End If
Return hasEnoughSpace
End Function ' end EnsureEnoughDiskSpace
End Module ' end Backup class
End Namespace ' end namespace
関連項目
タスク
[方法] プログラムを使用して単一のサイト コレクションのバックアップと復元を行う
[方法] バックアップと復元を実行できるコンテンツ クラスを作成する
参照
Microsoft.SharePoint.Administration.Backup
概念
SharePoint Foundation のバックアップ/復元オブジェクト モデルを使用したプログラミング