Tuesday, 11 February 2014

PowerShell - Extract all files modified within a date range in a web application in to CSV file

PowerShell - Extract all files modified within a date range in a web application in to CSV file :-

$UrlDochubWebApp = Read-Host "Enter destination web app url" # http://<site url>
$fromDate = Read-Host "Enter From Date (Format YYYY-MM-DD)"; # files modified start date
$toDate = Read-Host "Enter To Date (Format YYYY-MM-DD)"; # file modified end date
$SiteCollFilePath = Read-Host "Enter SIte collection csv details Path(folder path)"
#Loading Snap in for Microsoft.Sharepoint.Powershell
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{

Write-Host "Loading SharePoint Powershell Snapin" -ForegroundColor Green
$snapin = Add-PSSnapin "Microsoft.Sharepoint.Powershell"

Write-Host $snapin
}
$Webapplication =GEt-SPWebAPplication $UrlDochubWebApp
$SiteCollFilePath = "$SiteCollFilePath\ItemsCreated_$(get-date -format MMddyyHHmmss).csv";

$AllLibraryNames = New-Object "System.Collections.Specialized.StringCollection"
$AllLibraryNames.Add("library1") | Out-Null;
$AllLibraryNames.Add("library2") | Out-Null ;
$AllLibraryNames.Add("library3") | Out-Null ;
$AllLibraryNames.Add("library4") | Out-Null ;
$AllLibraryNames.Add("library5") | Out-Null ;
$dtToDate = Get-Date -Date $toDate
$dtFromDate = $dtFromDate.ToString("yyyy-MM-ddThh:mm:ss");
$dtToDate = $dtToDate.ToString("yyyy-MM-ddThh:mm:ss");
$strToBeInserted = "Site URL,Web Url,FileName,FileUrl,Created By,Created";

function LogData()
{
 Param ([string]$logstring)
Add-content $SiteCollFilePath -value $logstring
}

LogData $strToBeInserted;
if($Webapplication -ne $null)
{
$Allsites = $Webapplication.Sites
foreach($Site in $Allsites)
{
$siteUrl = $Site.Url;

foreach($web in $site.AllWebs)
{
try
{
$WebURl = $web.Url;
if(-not($web.Url.toLOwer() -match ("/scrapsite"))) # Condition to exclude a subsite named scrapsite..
{
foreach($list in $web.Lists)
{
$ListTitle = $list.Title
$LIstITemCount = $list.ItemCount;
if(($list.BaseType -eq "DocumentLibrary") -and ($AllLibraryNames.Contains("$ListTitle") ) -and ($LIstITemCount -gt 0))
{
$spQueryFilesAdded = New-Object Microsoft.SharePoint.SPQuery
$spQueryFilesAdded.Query="<Where><And><Geq><FieldRef Name='Created' /><Value Type='DateTime'>$dtFromDate</Value></Geq><Leq><FieldRef Name='Created' /><Value Type='DateTime'>$dtToDate</Value></Leq></And></Where>";
$spQueryFilesAdded.ViewAttributes="Scope='Recursive'";
$ItemsAdded = $list.getItems($spQueryFilesAdded);
if( $ItemsAdded.Count -gt 0)
{
foreach($item in $ItemsAdded)
{
$itemCreated = $item["Created"];
$itemCreatedBY = $item["Author"].ToString().Split("#".ToCharArray())[1];
$spFIle = $item.File;
$filename = $spFIle.Name;
$fileURl = $spFIle.URl;

$strToBeInserted = "$siteUrl,$WebURl,$filename,$fileURl,$itemCreatedBY,$itemCreated";

LogData $strToBeInserted;
}
}

}
}
}
}
finally
{
$web.Dispose();
}
}
}
}


No comments:

Post a Comment