Wednesday, 12 December 2018

Sharepoint 2013: Export-Import Method using PowerShell.


Add-PSSnapin microsoft.sharepoint.powershell

Export-SPWeb -Identity "http://sharepoint-u.com/sites/SiteCollectionName/Subsite" -ItemUrl "/sites/SiteCollection/Subsite/LibraryName/" -path "E:\temp\LibraryName.cmp" -IncludeUserSecurity -IncludeVersions ALL

Import-SPWeb -Identity "http://sharepoint2013.ntrs.com/sites/SiteCollection/LibraryName" -Path "E:\temp\LibraryName.cmp"

Wednesday, 8 August 2018

PowerShell: Script to Fetch all User's Data from User profile in SharePoint 2013


Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

    
$siteUrl =  "Enter here Central admin sharepoint URL"



$serviceContext = Get-SPServiceContext -Site $siteUrl
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext);
$profiles = $profileManager.GetEnumerator()

$fields = @(
            "SID",
            "ADGuid",
            "AccountName",
            "FirstName",
            "LastName",
            "PreferredName",
            "WorkPhone",
            "Office",
            "Department",
            "Title",
            "Manager",
            "AboutMe",
            "UserName",
            "SPS-Skills",
            "SPS-School",
            "SPS-Dotted-line",
            "SPS-Peers",
            "SPS-Responsibility",
            "SPS-PastProjects",
            "SPS-Interests",
            "SPS-SipAddress",
            "SPS-HireDate",
            "SPS-Location",
            "SPS-TimeZone",
            "SPS-StatusNotes",
            "Assistant",
            "WorkEmail",
            "SPS-ClaimID",
            "SPS-ClaimProviderID",
            "SPS-ClaimProviderType",
            "CellPhone",
            "Fax",
            "HomePhone",
            "PictureURL"
           )

$collection = @()

foreach ($profile in $profiles) {
   $user = "" | select $fields
   foreach ($field in $fields) {
     if($profile[$field].Property.IsMultivalued) {
       $user.$field = $profile[$field] -join "|"
     } else {
       $user.$field = $profile[$field].Value
     }
   }
   $collection += $user
}

$collection | Export-Csv -Path "E:\Output\sharepoint_user_profiles.csv"

Friday, 27 July 2018

How to Get the Last accessed Sites in SharePoint 2016/2013/2010?

SELECT @@SERVERNAME

CREATE TABLE #TempSites
(
[Database] varchar(500),
[Site URL] varchar(500),
TimeCreated datetime,
lastAccessDate datetime
)
exec sp_MSforeachdb

'INSERT INTO #TempSites SELECT ''?'',FullUrl AS [Site URL], TimeCreated,


DATEADD(d,DayLastAccessed + 65536, CONVERT(datetime, ''1/1/1899'', 101))

AS lastAccessDate FROM [?].dbo.Webs  WHERE

(DayLastAccessed <> 0) AND (FullUrl LIKE N''sites/%'') ORDER BY lastAccessDate'

SELECT * FROM #TempSites
=====================================================Run Above first==========

You will get the data copy in excel then Drop the table


Drop Table #TempSites

# Then Run this
SELECT COUNT(*) FROM sys.databases

To know that how many Total Database you have and compare with Excel DB counts.

Wednesday, 25 July 2018

Batch Script: Delete files older than 30 days


forfiles /p "C:\Users\ad395426\Desktop\Delete test" /s /m *.* /d -30 /c "cmd /c del @path"

PowerShell: Delete Files Older than 30 Days


Get-ChildItem –Path "Enter path of the folder" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item


Monday, 23 July 2018

SharePoint 2013: Get all the Last accessed sites


That we can get from DB side only as SharePoint PowerShell is not have any LastAccessedItem (Something as LastModifiedItem) property.

Run this DB script:-

SELECT FullUrl AS 'Enter the URL', TimeCreated,
DATEADD(d,DayLastAccessed + 65536, CONVERT(datetime, '1/1/1899', 101))
AS lastAccessDate FROM Webs WHERE
(DayLastAccessed <> 0) AND (FullUrl LIKE N'sites/%') ORDER BY LastAccessedDate

Friday, 20 July 2018

Recycle bin Script

Add-PSSnapin Microsoft.SharePoint.PowerShell

#Variables
$i = 0

#SharePoint Site Collection URL
$url = "http://apm.dev.jcallaghan.com"
#$url = Read-Host "Enter a valid URL to a SharePoint Site Collection?"
#if($url -eq ""){write-host "No URL provided." -foregroundcolor Red; Exit}

#How many days ago should items be deleted from?
$deleteFrom = -10
#$deleteFrom = Read-Host "Remove items older than how many days?"
#if($deleteFrom -eq ""){write-host "No value provided." -foregroundcolor Red; Exit}

#Create report in script path
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
$report = "$($dir)\DeletedSecondStateRecycleBinItems.csv"

#Date calculations
$dateNow = Get-Date
$dateDiff = $dateNow.AddMinutes(-$deleteFrom)
#$dateDiff = $dateNow.AddDays($deleteFrom)

#Display date/times for review in table
$table = @()
$review = New-Object System.Object
$review | Add-Member -type NoteProperty -Name "Date" -Value "Timestamp now"
$review | Add-Member -type NoteProperty -Name "Value" -Value $dateNow
$table += $review
$review = New-Object System.Object
$review | Add-Member -type NoteProperty -Name "Date" -Value "Files older than"
$review | Add-Member -type NoteProperty -Name "Value" -Value $dateDiff
$table += $review
$table | Format-Table –AutoSize

#Connect to the site
$site = Get-SPsite $url

#Report file and first row
New-Item $report -type file -Force | Out-Null
Add-Content $report "Deleted Items: $($dateNow)"
Add-Content $report "Name, Title, Deleted by, Deleted date, Path, File Guid"

#Get items from the Seconday Stage Recycle Bin (SSRB) that are older than are removel period.
$items = $site.Recyclebin | where { $_.ItemState -eq "SecondStageRecycleBin" -and $_.deleteddate -le $dateDiff}
$site.Recyclebin | where { $_.ItemState -eq "SecondStageRecycleBin" -and $_.deleteddate -le $dateDiff} | Format-Table -Property Title, Web, DeletedBy, DeletedDate -Autosize -Wrap

#Confirm there are items to delete
if($items -ne $null){

#Create prompt
$ok = New-Object System.Management.Automation.Host.ChoiceDescription "&OK","Description."
$cancel = New-Object System.Management.Automation.Host.ChoiceDescription "&CANCEL","Description."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($ok, $cancel)
$title = "Confirm"; $message = "Delete items from Second Stage Recycle Bin?"
$result = $host.ui.PromptForChoice($title, $message, $options, 1)

switch ($result) {
0{
#Get items to be deleted
$site.Recyclebin | where { $_.ItemState -eq "SecondStageRecycleBin" -and $_.deleteddate -le $dateDiff} | foreach{
#Add entry to report
Add-Content $report "$($_.LeafName),$($_.Title),$($_.deletedbyname),$($_.deleteddate),$($_.Dirname),$($_.Id)"

#Delete item by ID
$site.Recyclebin.Delete($_.ID)

$i++
}
write-host "$($i) items removed from Second Stage Recycle Bin."
}1{
write-host "Cancelled by user." -foregroundcolor Red
}
}
}else{
write-host "No files were found in the Second Stage Recycle Bin." -foregroundcolor Red
}

#Dispose
$site.dispose();
[/code]

Thursday, 19 July 2018

Site details


{
    Add-PSSnapin Microsoft.SharePoint.PowerShell
    $web = get-spweb (Read-Host "Enter Site URL")
        foreach ($list in $web.Lists)
            {
            if ($list.Title -eq "Pages")
                {
                foreach ($item in $list.Items)
                    {
                    $data = @{
               
                                "Web" = $web.Url
                                "list" = $list.Title
                                "Item ID" = $item.ID
                                "Item URL" = $item.Url
                                "Item Title" = $item.Title
                                "Item Name" = $item.Name
                                "Item Created" = $item["Created"]
                                "Item Modified" = $item["Modified"]
                                "File Size" = $item.File.Length/1KB
                            }
                    New-Object PSObject -Property $data
                    }
                }
            $web.Dispose();
            }
    }

Get-Documents | Out-GridView
#Get-Documents | Export-Csv -NoTypeInformation -Path c:\temp\inventory.csv


Wednesday, 18 July 2018

UserHits for Particular site

#Functions to Imitate SharePoint 2010 Cmdlets in MOSS 2007
function global:Get-SPWeb($url)
{
  $site= New-Object Microsoft.SharePoint.SPSite($url)
        if($site -ne $null)
        {
              $web=$site.OpenWeb();      
        }
    return $web
}
 
  
        #Method to Get Usage Data
        Function GetWebUsageData($Web)
        {
            try
            {
                #DataTable for Hits result - Because GetUsageData returns DataTable!
                $dtHits = New-Object System.Data.DataTable 
  
                $dtHits = $Web.GetUsageData("url", "lastMonth")
 
                if ($dtHits -ne $null)
                {
                    return ($dtHits);
                }
                else
                {
                    return ($null);
                }
            }
            catch
            {
                Write-Host $_.Exception.Message -ForegroundColor Red
                return ($null);
            }
        }
  
    $WebURL = "http://sharepoint.crescent.com/operations/sfdc/"
     
    $CurrentPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
    $OutPutFile = Join-path $CurrentPath "SiteUsageReport.txt"
     
    #Get the Web
    $Web = Get-SPWeb $WebURL
  
 
    #create a CSV file
    "Page `t Total Hits `t Last Accessed" > $OutPutFile #Write the Headers in to a text file
 
    #Get the Hits Data
    $HitsDT = GetWebUsageData($Web)
    if ($HitsDT -ne $null)
    {
        foreach($dr in $HitsDT)
        {
           
          $result = $webURL +"/" + $dr["Folder"]+"/"+$dr["Page"] + "`t" + $dr["Total Hits"] + "`t" + $dr["Most Recent Day"]
          $result >> $OutPutFile  #append the data
        }
    }