Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Thursday, March 18, 2021

How to list all sites and subsites in SharePoint Online using PowerShell?

function Get-SPOWebs(){

param(

   $Url = $(throw "Please provide a Site Collection Url"),

   $Credential = $(throw "Please provide a Credentials")

)


  $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)  

  $context.Credentials = $Credential 

  $web = $context.Web

  $context.Load($web)

  $context.Load($web.Webs)

  $context.ExecuteQuery()

  foreach($web in $web.Webs)

  {

       Get-SPOWebs -Url $web.Url -Credential $Credential 

       $web

  }

}

Saturday, January 23, 2021

Last Modified date for site collection?

 Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.Office.Server.Search.Query”)  


[String]$lastDate = "1/1/2018"


foreach($sc in $webapplication | Get-SPSite -Limit All)

{

    Write-Host $sc.Url -ForegroundColor Yellow


    $keywordQuery = New-Object Microsoft.Office.Server.Search.Query.KeywordQuery($sc)

    $keywordQuery.QueryText = "ContentClass:STS_ListItem AND LastModifiedTime>=$($lastDate) AND site:$($sc.Url)"

    $keywordQuery.RowLimit = 5;

    $searchExec = New-Object Microsoft.Office.Server.Search.Query.SearchExecutor

    $searchResults = $searchExec.ExecuteQuery($keywordQuery)


    If( 0 -eq $searchResults.Table.Count ){

        Write-Host "`tSite Collection $($sc.Url) is old" -ForegroundColor Red


}

Thursday, October 6, 2016

Cannot update Created By (Author) field through powershell

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
$SPWeb = Get-SPWeb "http://sharepoint";
$SPList = $SPWeb.GetList("http://sharepoint/Lists/Favorites");
$userName = "i:0#.w|[domain]\[username]";
$user = Get-SPUser -web $SPWeb -Identity $userName;

$SPListItem = $SPList.Items.Add();
$SPListItem["URL"] = "http://www.peakfinders.com";
$SPListItem["Author"] = $user;
$SPListItem.Update();

Thursday, March 17, 2016

Export the Subsite moved to site Collection Using PowerShell

Export the subsite


STSADM:

stsadm -o export -url "http://sharepointsite/sites/order/" -filename D:\backup.cmp -includeusersecurity -versions 4


Powershell:


Add-pssnapin microsoft.sharepoint.powershell

Import-SPWeb -identity "http://sharepointsite/sites/order/"  -path D:\backup.cmp -includeusersecurity  -force

Tuesday, March 15, 2016

How to get all default values for a document library

$FieldName = $list.Fields["NH Department"]
Write-Output $("NH Department - Default Value " + $FieldName.DefaultValue)

Wednesday, March 2, 2016

How to create site collections using SharePoint PowerShell 2013


Declare variable for template:

$template = Get-SPWebTemplate "STS#0"



New-SPSite -Name "VSPServer Intranet" -Url "http://peakfinders" –HostHeaderWebApplication $hnscWebApp -Template $template -OwnerAlias "Peakfinder\admin"

Thursday, February 18, 2016

Deleting all the items from a large list in SharePoint

Server Object Model:
string command = String.Format("<Method><SetList Scope=\"Request\">{0}</SetList><SetVar Name=\"ID\">{{0}}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar><SetVar Name=\"owsfileref\">{{1}}</SetVar></Method>", list.ID);
 
   SPQuery q = new SPQuery();
   q.RowLimit = 100;


   while (list.ItemCount > 0)
   {

    SPListItemCollection coll = list.GetItems(q);

    StringBuilder strval = new StringBuilder();
    strval .Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

    Guid[] ids = new Guid[coll.Count];
    for (int i=0;i<coll.Count;i++)
    {
     SPListItem item = coll[i];
     strval .Append(string.Format(command, item.ID.ToString(), item.File.ServerRelativeUrl));
     ids[i] = item.UniqueId;
    }
    strval .Append("</Batch>");
web.ProcessBatchData(strval .ToString());
 web.RecycleBin.Delete(ids);

    list.Update();
   }
  }

Powershell Script:


$siteUrl = "http://peakfinders/"
$listName = "Employee"
$batchSize = 100
$site = new-object Microsoft.SharePoint.SPSite($siteUrl)
$web = $site.OpenWeb()
$list = $web.Lists[$listName];
while ($list.ItemCount -gt 0)
{
  $batch = "<?xml version=`"1.0`" encoding=`"UTF-8`"?><Batch>"
  $i = 0

  foreach ($item in $list.Items)
  {
    $i++
    write-host "`rProcessing ID: $($item.ID) ($i of $batchSize)" -nonewline
    $batch += "<Method><SetList Scope=`"Request`">$($list.ID)</SetList><SetVar Name=`"ID`">$($item.ID)</SetVar><SetVar Name=`"Cmd`">Delete</SetVar><SetVar Name=`"owsfileref`">$($item.File.ServerRelativeUrl)</SetVar></Method>"
    if ($i -ge $batchSize) { break }
  }
  $batch += "</Batch>"
   write-host "Sending batch..."
  $result = $web.ProcessBatchData($batch)
  write-host "Emptying Recycle Bin..." 
  $web.RecycleBin.DeleteAll()
  write-host
  $list.Update()

}



Friday, February 12, 2016

How to Finding Column Display and Internal Names in Custom list using Powershell

$web = Get-SPWeb http://peakfinders
$list = $web.Lists["Employee"]
$list.fields | select Title, InternalName, Hidden, CanBeDeleted | sort title | ft -AutoSize

As you will most often be interested in the non-hidden fields, you can add a Where to filter them:

$list.fields | select Title, InternalName, Hidden, Sealed, CanBeDeleted | where {$_.Hidden -eq $false} | sort title | ft –AutoSize

Friday, January 29, 2016

Get all the site collection with content DB details using powershell commands

Get sites and content DB details using following power shell command

$rootSite=New-Object Microsoft.SharePoint.SPSite("http://weburl")
$spWebApp = $rootSite.WebApplication 
foreach($site in $spWebApp.Sites) {
    
    write-output "$($site.RootWeb.Url) - $($site.ContentDatabase)"     
  
    $site.Dispose() 

Wednesday, December 9, 2015

Programmatically Create SharePoint Toplink bar and Quicklaunch bar in SharePoint 2010 and 2013

Programmatically Create TopLink Bar in SharePoint site collection:

SPNavigationNodeCollection topnav = oweb.Navigation.TopNavigationBar;
SPNavigationNode node = new SPNavigationNode("Title", "URL");
node = topnav.AddAsLast(node);
node.Update();


Similarly, To create Quicklaunch bar

SPNavigationNodeCollection topnav = oweb.Navigation.QuickLaunch;
SPNavigationNode node = new SPNavigationNode("Title", "URL");
node = topnav.AddAsLast(node);
node.Update();

Wednesday, August 5, 2015

Import and Export subsite in SharePoint 2013 Using PowerShell Script

 Add-PSSnapin Microsoft.SharePoint.PowerShell


 Export-SPWeb "http://raghu/sites/test/test1" –Path "C:\rm.cmp" -includeusersecurity

 Import-SPWeb "http://raghu/sites/test/test1" -path "C:\rm.cmp" -IncludeUserSecurity

Tuesday, August 4, 2015

get SPWebTemplates Templates in SharePoint 2013

Add-PSSnapin Microsoft.SharePoint.PowerShell -ea silentlycontinue | Out-Null
Get-SPWebTemplate | ft ID, name, Title, Description -autosize -wrap








Monday, August 3, 2015

What is the full form of mdf, ldf and ndf in SQL Server?

SQL Server databases have three types of files:

Primary data files
The primary data file is the starting point of the database and points to the other files in the database. Every database has one primary data file. The recommended file name extension for primary data files is .mdf.

Secondary data files
Secondary data files comprise all of the data files other than the primary data file. Some databases may not have any secondary data files, while others have multiple secondary data files. The recommended file name extension for secondary data files is .ndf.

Log files
Log files hold all of the log information used to recover the database. There must be at least one log file for each database, although there can be more than one. The recommended file name extension for log files is .ldf.

SQL Server does not enforce the .mdf, .ndf, and .ldf file name extensions, but these extensions are recommended to help identify the use of the file.

Search Architecture Key points

Search :
Level
 1.web application
 2.site level
 1.webapplication when user creates using search center
 we need to config central admin
 1.incremental crawl -last updated items (we can set time every half/one hour user defined)
 2.full crawl -all items in web application (weekly once or day-wise ) Affects machine processing
 3.continous crawll -Each crawl dynmacally runs step by step Each process run serial process We need to create first search center in our webapplication under the subsute sitecollection-SharePoint Server Publishing Infrastructure manage site feature--sharePoint Server Publishing

Wednesday, July 29, 2015

how to remove Everyone permission for SP site and get SP users in sharepoint powershell

Add-PSSnapin Microsoft.SharePoint.PowerShell
Get-SPUser -web "http://raghu:2015/"


Remove-SPUser "c:0(.s|true" -web "http://raghu:2015/"

Tuesday, July 21, 2015

How to get login user Manager In SPServices In SHarepoint 2013

<script type="text/javascript">
$(document).ready(function() {


var managerName;
        var userName = $().SPServices.SPGetCurrentUser();
        $().SPServices({
            operation: "GetUserProfileByName",
            async: false,
            AccountName: userName,
            completefunc: function (xData, Status) {
                managerName = $(xData.responseXML).text();
                var managerLength = managerName.length;
                var indexofManager = managerName.indexOf("Manager");
                managerName = managerName.substring(indexofManager + 13, managerLength);
                var indexOffalse = managerName.indexOf("false");
                managerName = managerName.substring(0, indexOffalse);
            }
        });
        alert(managerName);
       
});
 UserProfile_GUID
- AccountName
- FirstName
- LastName
- PreferredName
- WorkPhone
- Office
- Department
- Title
- Manager
- AboutMe
- PersonalSpace
- PictureURL
- UserName
- QuickLinks
- WebSite
- PublicSiteRedirect
- SPS-Dotted-line
- SPS-Peers
- SPS-Responsibility
- SPS-Skills
- SPS-PastProjects
- SPS-Interests
- SPS-School
- SPS-SipAddress
- SPS-Birthday
- SPS-MySiteUpgrade
- SPS-DontSuggestList
- SPS-ProxyAddresses
- SPS-HireDate
- SPS-LastColleagueAdded
- SPS-OWAUrl
- SPS-ResourceAccountName
- SPS-MasterAccountName
- Assistant
- WorkEmail
- CellPhone
- Fax
- HomePhone

Friday, July 17, 2015

Freeze header in SharePoint List using JQuery?

Code:
Replace user list id
{B7EDD228-FDD2-46D2-A47E-E33D1D27E612}-{80AB3567-18AE-4ACE-A8E5-C86E5285E9C9}
<script type="text/javascript">

$(document).ready(function(){
var SummaryName ="Employee";
$("table").each(function(){
  var curTable = $(this).attr('id');

  if (curTable  == "{B7EDD228-FDD2-46D2-A47E-E33D1D27E612}-{80AB3567-18AE-4ACE-A8E5-C86E5285E9C9}"){

var $hdr = $("tr.ms-viewheadertr:first", $(this));
$(this).wrap("<div class='fh-tableWrapper' />");
$('.fh-tableWrapper').wrap("<div class='fh-outerWrapper' />");
$('.fh-outerWrapper').prepend("<div class='fh-bg' />");
$('th',$hdr).wrapInner("<div class='fh-thContentWrapper'/>");
$hdr.addClass("fh-thRow");
$(this).addClass('fh-table');

  }
});

});

</script>
<style type="text/css">

.fh-outerWrapper
{
    position:relative;
}

/* table wrapper*/
.fh-tableWrapper
{
    overflow:auto;
    height:300px;
}

/*the wrapper for 'th' content*/
.fh-thRow .fh-thContentWrapper{
    position:absolute;
    top:0;
}
.fh-bg
{
    position:absolute;
    top:0;
    height:30px;
    width:100%;
    background-color:#D5ECFF;

}

</style>

Thursday, July 16, 2015

How to particular site collection move new content database SharePoint Powershell Script

move-spsite "http://raghuspsserver/" -DestinationDatabase "raghu_contentdbnew"

Saturday, July 4, 2015

Do and Don't do n SharePoint Developement ,Best practices In SharePoint 2013,2010

When creating new columns, name them without any special characters or spaces.  After the column is created, rename it with the special characters or spaces.  This way the internal name is "clean".
When you are working with DataViews, some third party controls, and custom Webparts - you must use the internal name.  The potential for confusion is enormous.
When you are adding sites and pages make sure their names don't have spaces.

URLs
When adding pages or sites to your navigation, always browse to the intended destination; this will ensure your tabs will work properly.  In fact if you compare the resulting URL after you fix a broken tab this way, you will see that the URL must be relative, not absolute.

Use the same practice of giving the relative URL instead of the absolute URL in the Content Editor Webpart or Master Pages or in any other circumstance where you are required to provide the URL.

Whenever there is a requirement to change the URL in the Master Page wherein the Mater Page has been deployed as a feature, always change the link in the Master Page which is residing inside the Feature Folder and do not use SharePoint Designer to open a Site and Change the Link.

Backup/Restore or Export/Import

Never use Back Up and Restore procedure if you are trying to restore a Site Collection which is using Collaboration Portal, instead use Export and Import.

Same applies to saving of a collaboration site as template. MS does not support this.

STSADM
Get familiar with the various stsadm.exe commands. It helps a lot and saves time.
STSADM commands has been deprecated and will not be supported in future releases of Microsoft Sharepoint Foundation 2010.

SP Designer
Avoid using SharePoint Designer to edit any page design as much as possible. This causes a lot of performance issues.

Hive older backup
Please take the backup of the 12/14 hive if you are trying to do any changes inside the 12/14 hive.

Rollback Plan

Always have the rollback plan ready whenever you are deploying anything on the web server as SharePoint is very unstable so you would never know what is causing the problem very soon.

General
Learn to use the SharePoint object model efficiently.

Make sure that you always Dispose() the SPSite and SPWeb object in the finally block of your code.

Whenever you are required to loop through something, use for loop instead of foreach loop.

Try to avoid looping as much as possible. See if the same can be achieved through CAML query or SiteData Query or by using Search Object Model which actually fires the query on the crawled results.

Even if you are looping, try to reduce the number of loops as much you can.

Modularize your code and divide them into different parts depending on their functionality. Do not write bulky code.

Always put all your functions in try-catch block.

Never do any sort of Hard-Coding in your code.

Whenever there is more than one content DB for a web application for any reasons. Make sure that all the newly created sites goes to a particular content DB only and the data should not be going randomly to all the content DB’s. You can do this by setting the limitation for the number of sites in one of the content DB where you do not want the new data to go.

Make use of time bound caching wherever you are not required to show the real time data. Also you can use caching when you’re are pulling out data from a database and showing it in your Webpart. You have to set the Sql Dependency for the same.

Using Objects in Event Receivers
Do not instantiate an SPWeb, SPSite, SPList, or SPListItem object within an event receiver. Event receivers that instantiate these objects instead of using the instances passed via the event properties can cause the following issues:

Significant additional round-trips to the database (one write operation can result in up to five additional round-trips in each event receiver).
Calls to the Update method on these instances can cause subsequent Update calls in other registered event receivers to fail.
Usage of OOB files

Do not change OOB files. OOB files can be .aspx, .ascx ,.xsl, .xml, .js,.css  etc under 14 hive directory. Changing OOB can cause huge issues which cannot be traceable and changes will be visible to all applications that are running in the farm. If you want to use OOB files for customization purpose, create new folders, make a copy of the file and have it in the new folder and customize it.
For example,
If you wanna use/customize approve.aspx, create a new folder under  1033/layouts/<application name> , copy approve.aspx from 1033/layouts/ and paste it under 1033/layouts/<application name> and then customize it.

Saturday, June 27, 2015

SharePoint - How to Check Disk Space Usage

To determine your disk space usage: 
1. Click on "Site Settings". 
2. Click on "Go to site admin"
3. Click on "View Site Collection Usage Summary" - note that the maximum amounts listed may not agree with those outlined for your hosting plan. The amounts listed for your hosting plan are the correct limits. 
4. "View Storage Space Allocation" can help you determine exactly where space is being used.