My boss came to me and wanted to clean up some of our SharePoint lists.  We have an “Archived” flag on all of our document libraries so we can create views that will filter out stuff that isn’t needed anymore.  The problem with this is the list will never shrink.  I created a script for him to run that will download each of the files in the provided view and then delete them from SharePoint.  The ideal location to download the files to is somewhere that IT will backup regularly or a place that will be put into long term storage.  As always, feedback welcome.

Edit:  Added $WhatIf support

-Shane

[CmdletBinding()]
param(
    [Parameter(Mandatory=$True)]
    [string]$Site,
    [Parameter(Mandatory=$True)]
    [string]$ListName,
    [Parameter(Mandatory=$True)]
    [string]$ViewName,
    [Parameter(Mandatory=$True)]
    [string]$Destination,
    [Parameter(Mandatory=$True)]
    [string]$Username,
    [Parameter(Mandatory=$True)]

[string]$Password,

[switch]$WhatIf

)
 
$Pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$Pass
 
$proxy = New-WebServiceProxy -Uri "$Site/_vti_bin/Lists.asmx?WSDL" -Credential $Cred
$viewproxy = New-WebServiceProxy -Uri "$Site/_vti_bin/Views.asmx?WSDL" -Credential $Cred
$views = $viewproxy.GetViewCollection("$ListName")
$archiveView = $views.View | ? { $_.DisplayName -eq "$ViewName" }
 
$listitems = $proxy.GetListItems("$ListName",$($archiveView.Name),$null,$null,"50000",$null,"")
 
$WC = New-Object System.Net.WebClient
$Credential = New-Object System.Net.NetworkCredential -ArgumentList $Username,$Password
$WC.Credentials = $Credential
 
$listitems.data.row | % { 
 
    Write-Host "Downloading $Site/$($_.ows_LinkFileName)"

if($WhatIf –ne $True)

{

$WC.DownloadFile("$Site/$ListName/$($_.ows_LinkFileName)","$Destination\$($_.ows_LinkFileName)")

}

    
    [xml]$delete = @"
<Batch OnError="Continue" PreCalc="TRUE" 
ListVersion="0" 
ViewName="$($archiveView.Name)">
   <Method ID="1" Cmd="Delete">
      <Field Name="ID">$($_.ows_ID)</Field>
      <Field Name="FileRef">$Site/$ListName/$($_.ows_LinkFileName)</Field>
   </Method>
</Batch>
"@
 
Write-Host "Deleting $Site/$ListName/$($_.ows_LinkFileName) from SharePoint"
 

if($WhatIf –ne $True)

{

$proxy.UpdateListItems("$ListName",$delete) | Out-Null

}

    
}
Advertisements