Share via


Cómo: Hacer copias de seguridad de contenido mediante programación

Última modificación: jueves, 04 de noviembre de 2010

Hace referencia a: SharePoint Foundation 2010

En este tema se explica cómo programar una copia de seguridad de un componente de contenido de SharePoint Foundation, y se supone que conoce los temas Introducción a la copia de seguridad y restauración de datos en SharePoint Foundation y Programación con el modelo de objetos de copia de seguridad y restauración de SharePoint Foundation.

Para hacer una copia de seguridad un componente de contenido

  1. Agregue una referencia a Microsoft.SharePoint al proyecto de Visual Studio y agregue instrucciones using para los espacios de nombres Microsoft.SharePoint.Administration y Microsoft.SharePoint.Administration.Backup a su archivo de código.

  2. En el método Main, indique al usuario que especifique dónde se debe almacenar la copia de seguridad.

    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()
    
  3. En el método Main, cree un objeto SPBackupSettings mediante el método GetBackupSettings estático. Para el primer parámetro, pase la ruta de acceso donde se debe almacenar la copia de seguridad. Para el segundo parámetro, pase una cadena de versión de uno de los valores de SPBackupMethodType.

    SPBackupSettings settings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full");
    
    Dim settings As SPBackupSettings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full")
    
  4. Indique al usuario que especifique el componente de contenido del que hacer copia de seguridad y asigne su nombre a la propiedad IndividualItem. Para ver un desglose de los nombres de los componentes del conjunto de servidores que pueden ser los objetos de las operaciones de copia de seguridad, puede ejecutar el comando stsadm -o backup -showtree en la línea de comandos del servidor o visitar Operaciones > Realizar una copia de seguridad en la aplicación Administración central. Para especificar el conjunto de servidores completo, use "Farm" como nombre (si se establece la propiedad en null también se selecciona todo el conjunto de servidores para la copia de seguridad y se da por supuesto que utiliza IndividualItem en el código subsiguiente para identificar por el nombre el componente del que se hará copia de seguridad. Para ver ejemplo, consulte el uso del método FindItems() en el paso 8).

    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()
    
  5. Si lo desea, establezca una o más de las propiedades IsVerbose, UpdateProgress y BackupTheads() (para obtener más información sobre estas propiedades, consulte los temas de referencia respectivos).

    settings.IsVerbose = true;
    settings.UpdateProgress = 10;
    settings.BackupThreads = 2;
    
    settings.IsVerbose = True
    settings.UpdateProgress = 10
    settings.BackupThreads = 2
    
  6. Cree la operación de copia de seguridad con el método CreateBackupRestore(). (También se crea un objeto de historial de la operación. Para obtener más información, consulte SPBackupRestoreHistoryObject y SPBackupRestoreHistoryList).

    Guid backup = SPBackupRestoreConsole.CreateBackupRestore(settings);
    
    Dim backup As Guid = SPBackupRestoreConsole.CreateBackupRestore(settings)
    
  7. Si la interfaz de usuario indica a los usuarios que escriban el nombre de componente en lugar de elegirlo de una lista, debe asegurarse de que el nombre especificado coincida exactamente con un componente. Agregue la siguiente línea al método Main.

    SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref backup);
    
    Dim node As SPBackupRestoreObject = EnsureUniqueValidComponentName(settings, backup)
    
  8. Agregue la siguiente implementación del método EnsureUniqueValidComponentName. Utilice el método FindItems() para recuperar una colección de objetos de contenido cuyo nombre coincida con el nombre escrito por el usuario. Si no hay ninguna coincidencia, indique al usuario que vuelva a intentarlo. Si hay más de uno, indique al usuario que sea más específico. Si el nombre de componente que el usuario especifica es válido y no ambiguo, obtenga una referencia al objeto SPBackupRestoreObject que representa el componente que el usuario desea restaurar.

    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
    
  9. En el método Main, cree una marca Boolean que señale si hay suficiente espacio para la copia de seguridad, y una estructura condicional que se ejecutará solo si el método EnsureUniqueValidComponentName devuelve un nodo válido.

    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
    
  10. Agregue la siguiente implementación del método EnsureEnoughDiskSpace. Utilice el método DiskSizeRequired() para obtener la cantidad de espacio que se necesita y el método DiskSize() para determinar la cantidad de espacio libre disponible en el disco de destino.

    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
    
  11. En el método Main, cree una estructura condicional que se ejecutará sólo si EnsureEnoughDiskSpace devuelve 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
    
  12. Reemplace la línea "TODO" del paso anterior con el código siguiente. Esto establece la operación como la operación activa con el método SetActive() y comprueba si se ha realizado correctamente. Si se produce un error, cosa que sucederá si otra operación de copia de seguridad o restauración ya está en curso, informe del error a la interfaz de usuario de la aplicación.

    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
    
  13. En la bifurcación de código que se ejecuta si la llamada a SetActive() se hace correctamente, ejecute la operación con el método Run(). Compruebe que la operación se completa correctamente. Si se produce un error, envíe el mensaje de error de la operación a la interfaz de usuario. En el siguiente código se reemplaza la línea "TODO" del paso anterior.

    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
    
  14. Limpie la restauración con el método Remove(). Agregue el siguiente código justo antes de la llave de cierre que ha insertado en el paso 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()
    

Ejemplo

En el código siguiente se muestra cómo programar una copia de seguridad de un componente de contenido.

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

Vea también

Tareas

Procedimiento para realizar la copia de seguridad y restaurar una única colección de sitios mediante programación

Procedimiento para restaurar contenido mediante programación

Procedimiento para crear una clase de contenido que se pueda restaurar y de la que se pueda hacer una copia de seguridad

Procedimiento para ampliar la utilidad STSADM

Referencia

Microsoft.SharePoint.Administration.Backup

Backup

Restore

Conceptos

Programación con el modelo de objetos de copia de seguridad y restauración de SharePoint Foundation

Otros recursos

Herramienta de línea de comandos Stsadm.exe