Showing posts with label Document Library. Show all posts
Showing posts with label Document Library. Show all posts

Friday, 4 July 2014

PowerShell - List out all checked out documents in library

PowerShell - List out all checked out documents in library:-
Note:-
Library names needs to be hard coded inside code, at present dummy entries are made, replace it with actual library name before script execution.

Input:-
1. Enter web app url
2. Create a csv file with all site collection url and pass the path of the same.
Code:-
$UrlDochubWebApp = Read-Host "Enter destination web app url"
$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\ItemsCheckedOut_$(get-date -format MMddyyHHmmss).csv";

$AllLibraryNames = New-Object "System.Collections.Specialized.StringCollection"
$AllLibraryNames.Add("<LibraryName-1>") | Out-Null;
$AllLibraryNames.Add("<LibraryName-2>") | Out-Null ;
$AllLibraryNames.Add("<LibraryName-3>") | Out-Null ;

$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;
$siteTitle = $site.Title;
foreach($web in $site.AllWebs)
{
try
{
$WebURl = $web.Url;
if(-not($web.Url.toLOwer() -match ("/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))
{
$files = $list.CheckedOutFiles;
foreach($file in $files)
{
$filename = $file.LeafName;
#$fileURl = $file.URl;
$fileDIr = $file.DirName ;
$fileURl="$fileDIr/$filename";
$itemCreated = $file.TimeLastModified;
$itemCreatedBY = $file.CheckedOutByName;
$strToBeInserted = "$siteUrl,$WebURl,$filename,$fileURl,$itemCreatedBY,$itemCreated";
LogData $strToBeInserted;
}
}
}
}
}
finally
{
$web.Dispose();
}
}
}
}




PowerShell - Script used to get list of files with same name in document library

PowerShell - Script used to get list of files with same name in document library:-
Input:-
1. Pass site URL and List name as input to the function to generate log with list of files with same name in that library.

Code:-
$LogFilePath =  Read-Host "Enter Log file path (C:/...../Log.txt)"

# =========================== LOADING SHAREPOITN POWERSHELL SNAPIN FILE DETAILS =====================================
$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

}

function Get-SPFilesInList
{
    param ($Url, $ListName)
 
    $web = Get-SPWeb -Identity $Url
    $list = $web.Lists.TryGetList($ListName)
    $folderExists=$false;  

    if ($list -ne $null)
    {
        #write-host $ListName $list.Items.count;
        $ItemsColl = $list.Items
        foreach ($item in $ItemsColl)
        {
            $documentType='';
    $docTypeWIthValues= $item["Debt Document Type"]
    if($docTypeWIthValues -ne $null)
    {
    $doctypeParts=$docTypeWIthValues.toString().split('|');
    $documentType= $doctypeParts[0];
    }
            #write-host $documentType
          [string]$fileNameWithExt=$item.File.Name;
          [string]$fileName = [System.IO.Path]::GetFileNameWithoutExtension($item.File.Name);
          #[string]$fileName = $item.File.Name;
          #write-host $fileName
          [int]$sameFileNameCount = 0        
          foreach ($itemToCompare in $ItemsColl)
            {
                [string]$fileNameToCompare = [System.IO.Path]::GetFileNameWithoutExtension($itemToCompare.File.Name);
                #[string]$fileNameToCompare = $itemToCompare.File.Name;
                if ($fileName -eq $fileNameToCompare)              
                {
                    $sameFileNameCount=$sameFileNameCount+1
                }
            }          
            if ($sameFileNameCount -gt 1)
            {
                #write-host $item.File.Name "- " $sameFileNameCount " files exists with this name"
                [string]$fileurl=$item.Url
                $fileurl="$Url/$fileurl"
                $msg = "$global:Xref,$global:AssetID,`"$ListName`",`"$fileNameWithExt`",`"$fileName`",`"$documentType`",`"$fileurl`""   |  Out-File $LogFilePath -append
             
            }
           <# $itemSize = (($item.File.Length)/1024)/1024
            if($itemSize -Ge $fileSize)
            {
               $itemUrl = $item.Web.Url + "/" + $item.Url;
               Write-Host $itemUrl ", File size:: " $('{0:N2}' -f $itemSize) MB -ForegroundColor Green
            }#>
        }
     
        #[System.IO.Path]::GetFileNameWithoutExtension("Test Config.xlsx")
        <#foreach ($SubFolder in $list.RootFolder.SubFolders)
        {
            if ($SubFolder.Name -eq $FolderName)
            {
                $folderExists=$true;
                break;
            }                    
        } #>    
        <#if($folderExists -eq $false)
            {
                #Create a Folder
                $folderItem = $list.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $FolderName)
                $folderItem.Update();            
             
                $msg = "$Url, $FolderName, folder created, $ListName"  |  Out-File $LogFilePath -append
                write-host "$Url $FolderName folder created in $ListName." -foregroundcolor green
            }
            else
            {
                $msg = "$Url, $FolderName, folder already exists, $ListName"  |  Out-File $LogFilePath -append
                write-host "$Url $FolderName folder already exists in $ListName." -foregroundcolor yellow
            }#>
    }
    $web.Dispose()

}

[Microsoft.SharePoint.SPSecurity]::RunWithElevatedPrivileges(
{
    Write-Host "Process Started...Time - $(get-date -format HH:mm:ss)" -Foregroundcolor Yellow
    LoadWSSAssembly;
    $StartTime=Get-Date
    $msg = "Xref,Loan Number,Library Name,File Name,Common Name,Document Type,Path"  |  Out-File $LogFilePath -append
   Get-SPFilesInList "<Site URL>", "<List Name>"

    $StartTime=(Get-Date) - $StartTime
    write-host "Total execution time- " $StartTime
    Write-Host "Process Completed...Time - $(get-date -format HH:mm:ss)" -Foregroundcolor Yellow

})


Tuesday, 11 February 2014

PowerShell - Update default list view by adding 2 columns for all site under all site collection under specified Managed Path

PowerShell - Update default list view by adding 2 columns for all site under all site collection under specified Managed Path:-

<#
.SYNOPSIS
   <A brief description of the script>
.DESCRIPTION
   <A detailed description of the script>
.PARAMETER <paramName>
   <Description of script parameter>
.EXAMPLE
   <An example of using the script>
#>

$UrlDochubWebApp = Read-Host "Enter destination web app url"

$FieldPropetyInternalname = "Property"; # column 1
$FieldTitleInternalname = "Title"; # Column 2

#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
}

function updateView($list)
{
$View = $list.DefaultView;
$ViewFields = $View.ViewFields;
try
{
if(!$ViewFields.Exists($FieldTitleInternalname))
{
$ViewFields.add($FieldTitleInternalname);
$ViewFields.MoveFieldTo($FieldTitleInternalname,2);
}
if(!$ViewFields.Exists($FieldPropetyInternalname))
{
$View.ViewFields.add($FieldPropetyInternalname);
$View.ViewFields.MoveFieldTo($FieldPropetyInternalname,4);
}
$View.update();
}
catch [System.Exception]
{
Write-Host $_;
}

}

function updateLIbraries()
{
 $Webapplication =GEt-SPWebAPplication $UrlDochubWebApp


$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 ;
if($Webapplication -ne $null)
{
$Allsites = $Webapplication.Sites
foreach($Site in $Allsites)
{
$siteUrl = $Site.Url;

foreach($web in $site.AllWebs)
{
try
{
$WebURl = $web.Url;
if(($web.Url.toLOwer() -match ("/debt/"))) # Condition to check managed path
{
$WebURl = $web.Url;
$allLists = $web.Lists;
$alllistsCount = $allLists.Count;
for($counter = 0;$Counter -lt $alllistsCount;$counter++)
{
$list = $allLists[$counter];
$ListTitle = $list.Title
$LIstITemCount = $list.ItemCount;
if(($list.BaseType -eq "DocumentLibrary") -and ($AllLibraryNames.Contains("$ListTitle") ) )
{
updateView $list;
}
}
Write-Host "Updated for $WebURl";
}
}
finally
{
$web.Dispose();
}
}
}
}

}

updateLIbraries;



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();
}
}
}
}