Como descargar archivos adjuntos de una lista de SharePoint 2013 con PowerShell

Con el script detallado anteriormente es posible descargar los archivos adjuntos de una lista, asimismo se puede dejar un archivo log con los registros que fueron descargados correctamente, o registrar los archivos que tuvieron problemas al descargar, de un determinado rango de fechas previamente fijadas en los parámetros.

#En esta sección pides lo parámetros como ser servidor, carpeta donde descargaras el adjunto, el rango de fecha, y persistencia coloca 1 por defecto (1 Descarga los adjuntos 0 No descarga ) 
Param ( 
[Parameter(Mandatory=$True)] 
[ValidateNotNull()] 
[string]$SourceWebURL = "http://tuservidor", 
[Parameter(Mandatory=$True)] 
[ValidateNotNull()] 
[string]$DownloadPath = "C:\Archivos\documentos\", 
[Parameter(Mandatory=$True)] 
[ValidateNotNull()] 
[datetime]$FechaDesde = "02/01/2016", 
[Parameter(Mandatory=$True)] 
[ValidateNotNull()] 
[datetime]$FechaHasta = "02/29/2016", 
[Parameter(Mandatory=$True)] 
[ValidateNotNull()] 
[bool]$Persistence = $false 
) 
#funcion que guarda los log. 
#=================================================================== 
Function LogWrite([string]$logstring, [bool]$toConsole = $false#=================================================================== 
{ 
   if ($Persistence) { Add-content $FileLogName -value $logstring } 
   if ($toConsole) { Write-Host $logstring } 
} 
 
#=================================================================== 
Function PauseKey($Message = "Presione ENTER para continuar ... "#=================================================================== 
{ 
    try { 
        Write-Host -NoNewline $Message 
        #$KeyInfo = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") 
        $key = [system.console]::readkey($true) 
    } 
    catch { 
            $Shell = New-Object -ComObject "WScript.Shell" 
            $Button = $Shell.Popup($Message, 0, "Script Paused", 0) 
    } 
    Write-Host 
    #En esta sentencia acepta el control C para teminar la ejecución 
    if ([console]::KeyAvailable) 
    { 
        $key = [system.console]::readkey($true) 
        if (($key.modifiers -band [consolemodifiers]"control"-and ($key.key -eq "C")) 
        { 
          Write-Host "Terminando..." 
          exit # break 
        } 
    } 
} 
# 
Clear-Host 
$ErrorActionPreference = "Stop";  
#Guarda en este archivo todos los errores  
$FileLogName = get-date -uformat "MiLog_%Y-%m-%d-%H-%M-%S.Log"  
$ver = $host | select version 
if ($Ver.version.major -gt 1)  
{ 
    $Host.Runspace.ThreadOptions = "ReuseThread" 
} 
if (!(Get-PSSnapin Microsoft.SharePoint.PowerShell -ea 0)) 
{ 
    Write-Progress -Activity "Cargando Modulos" -Status "Cargando Microsoft.SharePoint.PowerShell" 
    Add-PSSnapin Microsoft.SharePoint.PowerShell 
} 
# 
try { 
    $strFechaDesde = "$($FechaDesde.ToString('yyyy-MM-ddT00:00:00Z'))" 
} 
catch { 
    Write-Host -ForegroundColor Red $_.Exception.ToString() 
    exit; 
} 
# 
try { 
    $strFechaHasta = "$($FechaHasta.ToString('yyyy-MM-ddT23:59:00Z'))" 
} 
catch { 
    Write-Host -ForegroundColor Red $_.Exception.ToString() 
    exit; 
} 
# 
try { 
    $sWeb = Get-SPWeb $SourceWebURL 
} 
catch { 
    Write-Host -ForegroundColor Red $_.Exception.ToString() 
    exit; 
} 
# 
PauseKey("Presione cualquier tecla para iniciar ... "); 
#Adiciono el nombre de mi lista, la cual voy a descargar los adjuntos 
$SourceLibraryTitle = "Mibiblioteca" 
$sList = $sWeb.Lists[$SourceLibraryTitle$spQuery = New-Object Microsoft.SharePoint.SPQuery 
$spQuery.ViewFieldsOnly = $true 
$spQuery.ViewAttributes = "Scope = 'Recursive'" 
$spQuery.RowLimit = $sList.ItemCount; 
#Aqui creamos la consulta en el rango de fecha que queremos descargar 
$spQuery.Query = [System.String]::Format(" 
<Where> 
     <And> 
        <Geq> 
           <FieldRef Name='Created' /> 
           <Value IncludeTimeValue='TRUE' Type='DateTime'>{0}</Value> 
        </Geq> 
        <Leq> 
           <FieldRef Name='Created' /> 
           <Value IncludeTimeValue='TRUE' Type='DateTime'>{1}</Value> 
        </Leq> 
     </And> 
</Where>", $strFechaDesde$strFechaHasta ); 
# 
$items = $sList.GetItems($spQuery); 
$count = $items.Count; 
# 
$ItemMoveCount=0; 
$txtMesagge = "Descargando (" + [string]$count + " items) desde " + $SourceWebURL + "/" +  
              $SourceLibraryTitle + " hasta " + $DownloadPath + 
              " (" + $strFechaDesde + " : " + $strFechaHasta + ") ..."#guardamos el log     registro por registro       
LogWrite "." $true; 
LogWrite $txtMesagge $true; 
LogWrite "." $true#Luego se recorre la lista para descargar los adjuntos 
foreach ($theItem in $items) 
{ 
    Write-Host -NoNewline -foregroundcolor Red "."; 
 
    $theAttachments = $theItem.Attachments; 
    if ($theAttachments.Count -eq 0) 
    { 
        continue; 
    } 
    foreach ($attach in $theAttachments) 
    { 
        $strID = $theItem.ID; 
        $strCreated = $theItem["Created"]; 
        $Url = $theAttachments.UrlPrefix + $attach; 
        $file = $sWeb.GetFile($Url); 
        $bytes = $file.OpenBinary(); 
        $FilePath = $DownloadPath + "\" + $strID + "_" + $attach; 
        if ($Persistence) { 
            $fs = new-object System.IO.FileStream($FilePath"OpenOrCreate"); 
            $fs.Write($bytes, 0 , $bytes.Length);    
            $fs.Close(); 
        } 
        $msg = $strCreated.ToString() + " " + $FilePath; 
        LogWrite $msg; 
    } 
    $ItemMoveCount++; 
} 
Write-Host ""

Atte.
Ademir 


Comentarios

Entradas más populares de este blog

Que es un Webpart o Elemento Web en SharePoint?

The type or namespace name ‘SharePoint’ does not exist in the namespace ‘Microsoft’ (are you missing an assembly reference?) – SharePoint 2013 Client Object Model dlls

Extender el periodo de Evalución hasta 240 días en SQL Server y SharePoint Server