Search This Blog

Wednesday, November 19, 2014

PowerShell Scripts in SharePoint


What is PowerShell?

It is a Extendable and scripting language can be used to manage and administer server environments in SharePoint. Using Poweshell we can do tasks easier

WHAT IS POWERSHELL EXACTLY?
Microsoft's task automation framework
› Command Line Shell
› Scripting Language
› Built on and integrated with the .NET Framework
› (Pretty much C# syntax with a few caveats)
DOS on steroidsWHERE IS POWERSHELL?
Built into Windows Server 2008 R2 and Windows 7
Older OS – Windows Management Framework
Start > Accessories > Windows PowerShell
SharePoint 2010 Management Shell
› Shortcut to a profile that loads the SP2010 Provider Snapin
STSADM?
Still there and still works
› backwards compatibility
› Allows for portability of existing STSADM batch files and scripts
Don’t use this as a crutch! You should do everything in PowerShell.
› PowerShell has full access to the SharePoint API from the
command line

BENEFITS OF POWERSHELL
Interact with .NET objects directly
Remoting interface
Reduction in the need of some 3rd party solutions
Perform administrative functions in bulk, reducing time and effort.
Performance benefits for batch operations and scheduling
Some SharePoint functions require the use of PowerShell:
› Adding Custom Solutions(2010+)
› Resetting the Farm Passphrase (2010+)
› Configuring the State Service Application (2010+)
› Configuring the Publishing Feature’s Super User Accounts(2010+)
› Pretty much all Search configuration in 2013POWERSHELL ISE
Windows PowerShell Integrated
Scripting Environment (ISE)
• Can run commands, write, test, and debug scripts
• Uses color-coding
• Only available with PS 2.0 and above

VARIABLES
Begin with $
$integer = 100
$string = “Hello World!”
$web = Get-SPWeb http://portal.com
$WEB = $web = $Web (Not Case Sensitive!)
OPERATORS
$integer = 100
$integer = 100+1
Write-Host $integer  101
$integer = $integer * 2
Write-Host “Integer = $integer”  Integer = 202
Get-Help about_operators
SPECIAL VARIABLES
Reserved values: $TRUE, $FALSE, $NULL
$_ Current object in the Pipeline
$Args Array of parameters passed to script
$PsCmdLet Current CMDLET or function that is running
$Pwd Current Working Directory (not Password)

COMPARISON OPERATORS
Operator   
Name     
Example   
Result

eq               
Equal
3 - eq 3     
True
ne            
Not Equal      
3 -ne 3   
False
-lt               
Less Than       
3 -lt 3    
False
-le 
Less Than or Equal To    
3 -le 3  
True
-gt                
Greater Than 
3 -gt 3      
False
-ge              
Greater Than or Equal To    
3 -ge 3   
True

COMPARISON OPERATORS (CONT.)
Operator
Example
Result

-like
“PowerShell” -like “*shell”
True
-notLike
Uses Wildcard


-match
“9” -match “[0-9]”
True
-notMatch
Uses Regular Expression


-contains
“abc”,”def” -contains “def”
True






 LOOPING
For
For Each
Do While
Do UntilFOREACH-OBJECT
Easy Enumeration in Command Line
…Something… | foreach-object { …code…}
› cls
› $web = Get-SPWeb http://portal.contoso.com
› $web.Webs | ForEach-Object {$_.Title}

FORMATTING
| Sort-Object
Get-EventLog system -Newest 5 | Sort-Object EventId
| Format-Table
| Format-ListSCRIPTS
Allow complex command combinations
Consistently repeat frequent and/or complex tasks
Can be parameterized
.PS1 files even though we are 2.0
› $HOST.Version gets current PS version
COMMENTS
We needed another comment format… 
# for single lines
#This is a comment
This is not
<# #> for multiple lines
<# Multiple Line
Comments#>
INPUT/OUTPUT
Read-Host (waits for user input)
   $var = Read-Host “Prompt Text”
Write-Host “Writes this text to the console”
Write-Host $var –nonewline
Write-Host (3,9,27,81) –separator “ , “
To write to file:
>> <filename>
| Output-File <filename>
|Tee <filename>
WHAT TO REMEMBER
Set-Execution Policy
Get-Help (Get-Help About)
Get-Command (Alias GCM)
Get-Member
Add-PSSnapIn
AliasesALWAYS


How to get a list of site collection for a web application using PowerShell Script
How to get a list of site collection with template for a web application

       The following PowerShell  script can be used to get a list of site collections with template for a web application.

Get-SPSite -WebApplication http://c4968397007/-Limit All |
Select -ExpandProperty AllWebs |
ft url, Title,WebTemplate, Created -auto |
out-string -width 1024 > c:\sites\sitetemplate.txt

How to get a list of site collections without template names for a web application

     This script will get only list of site collections without template names for a web application.

function GenerateAllSitecollections ($url)
{
    try
      {
         $Site=Get-SPSite $url        
         $spWebApp = $Site.WebApplication
         $TotalList = @()
          write-host "Below is the list of all site collections for a web application" + $spWebApp + "….." -foregroundcolor red
         foreach($allsites in $spWebApp.Sites)
         {
           $list =  $allsites.url
                   $listtemplatename = $allsites.WebTemplate
           write-host $list –foregroundcolor  blue   
                   write-host $listtemplatename -foregroundcolor blue  
         }                      
      }
   catch
      {
          write-host "Unable to Extract Site collection List in web application" -foregroundcolor red
          break
      }

GenerateAllSitecollections  -Url " http://c4968397007/" > c:\sites\sitecollections.txt

How to remove SPWebApplication using powershell script in SharePoint 2013


         Remove-SPWebApplication cmdlet deletes the Web application specified by the Identity and Zone parameters. If no zone is provided, the entire Web application and all zones are removed.

Remove particular zone:


  
  Get-SPWebApplication "http://sitename"|Remove-SPWebApplication -Zone "Intranet" -Confirm

    
Identity: http://sitename. 

             It removes the Internet zone Web application extension on the Web application at http://sitename. This command does not remove the content databases or the IIS Web site.


Remove Perticular web application content databases and IIS website :


 
Remove-SPWebApplication http://sitename -Confirm -DeleteIISSite -RemoveContentDatabases

         It removes the Web application, all content databases, and the IIS Web site at
http://sitename



Approve masterpage using PowerShell in SharePoint
           I have a problem with my custom masterpage approve, i have edited my masterpage, save the page and check-in the masterpage but i con't able to approvel the masterpage. To solve this issue i use one PowerShell Script.

 The following PowerShell Script will help you to approve the masterpage in SharePoint.

$SPWeb = Get-SPWeb "http://localhost/site/mysite"
$file = $SPWeb.GetFile("_catalogs/masterpage/v4_my.master")
$file.CheckIn("")
$file.Publish()



How to Export particular Group in Term Store Management in SharePoint 2013
  The following PowerShell script can be used to Export  particular Group in Term Store Management in SharePoint 2013. Here we have to give 'Site Collection','Name of the group' and 'Path' where we have to save the group.

param(
    [string]$siteUrl = "
site collection",
    [string]$termGroup = "
Name_Of_Term_Store",
    [string]$exportPath = "
C:\export1"
)


function Add-Snapin {
    if ((Get-PSSnapin -Name Microsoft.Sharepoint.Powershell -ErrorAction SilentlyContinue) -eq $null) {
        $global:SPSnapinAdded = $true
        Write-Host "Adding SharePoint module to PowerShell" -NoNewline
        Add-PSSnapin Microsoft.Sharepoint.Powershell -ErrorAction Stop
        Write-Host " - Done."
    }

    Write-Host "Adding Microsoft.SharePoint assembly" -NoNewline
    Add-Type -AssemblyName "Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
    # Disable the above line and enable the line below for SharePoint 2013
    # Add-Type -AssemblyName "Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
    Write-Host " - Done."
}

function Remove-Snapin {
    if ($global:SPSnapinAdded -eq $true) {
        Write-Host "Removing SharePoint module from PowerShell" -NoNewline
        Remove-PSSnapin Microsoft.Sharepoint.Powershell -ErrorAction SilentlyContinue
        Write-Host " - Done."
    }
}

function Get-ScriptDirectory
{
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value
    return Split-Path $Invocation.MyCommand.Path
}

function Export-SPTerms {
    param (
        [string]$siteUrl = $(Read-Host -prompt "Please provide the site collection URL"),
        [string]$termGroupName = $(Read-Host -prompt "Please provide the term group name to export"),
        [string]$saveLocation = $(Read-Host -prompt "Please provide the path of the folder to save the CSV file to")
    )

    if ([IO.Directory]::Exists($saveLocation) -eq $false)
    {
        New-Item ($saveLocation) -Type Directory | Out-Null
    }

    Write-Host "Getting Taxonomy Session";
    $taxonomySession = Get-SPTaxonomySession -site $siteUrl
    $taxonomyTermStore =  $taxonomySession.TermStores | Select Name
    $termStore = $taxonomySession.TermStores[$taxonomyTermStore.Name]
    $fileRootNoteCreated = $false;

    # Ampersands are stored as full width ampersands (see http://www.fileformat.info/info/unicode/char/ff06/index.htm)
    [Byte[]] $amp = 0xEF,0xBC,0x86

    Write-Host "Looping through Term store Groups to find: '$termGroupName'"
    foreach ($group in $termStore.Groups) {
        Write-Host "Checking: '$($group.Name)'"
        $groupName = $group.Name.Replace([System.Text.Encoding]::UTF8.GetString($amp), "&");
        if ($groupName -eq $termGroupName) {
    
            Write-Host "Looping through Term sets"
            foreach ($termSet in $group.TermSets) {
                # Remove unsafe file system characters from file name
                $parsedFilename =  [regex]::replace($termSet.Name, "[^a-zA-Z0-9\\-]", "_")
            
                $file = New-Object System.IO.StreamWriter($saveLocation + "\termset_" + $parsedFilename + ".csv")
            
                # Write out the headers
                #$file.Writeline("Term Set Name,Term Set Description,LCID,Available for Tagging,Term Description,Level 1 Term, Level 2 Term,Level 3 Term,Level 4 Term,Level 5 Term,Level 6 Term,Level 7 Term")
                $file.Writeline("<termStore Name='" + $termStore.Name + "' GUID='" + $termStore.ID + "' Group='" + $groupName + "'>");
                $file.Writeline("`t<termSet Name='" + $termSet.Name + "' GUID='" + $termSet.ID + "' Description='" + $termSet.Description + "'>");
                try {
                    Export-SPTermSet $termSet.Terms
                }
                finally {
                    $file.Writeline("`t</termSet>");
                    $file.Writeline("</termStore>");
                    $file.Flush()
                    $file.Close()
                }
            }
        }
    }
}

function Export-SPTermSet {
    param (
        [Microsoft.SharePoint.Taxonomy.TermCollection]$terms,
        [int]$level = 1,
        [string]$previousTerms = ""
    )

    $tabCount = $level+1;
    if ($level -gt 1) {$tabCount = $tabCount + ($level-1);}

    if ($terms.Count -gt 0)
    {
        $file.Writeline("`t" * $tabCount + "<terms>");
    }

    if ($level -ge 1 -or $level -le 7)
    {
        if ($terms.Count -gt 0 ) {
            $termSetName = ""
            if ($level -eq 1) {
                $termSetName =  """" + $terms[0].TermSet.Name.Replace([System.Text.Encoding]::UTF8.GetString($amp), "&") + """"
            }
            $terms | ForEach-Object {
                $termName = $_.Name.Replace([System.Text.Encoding]::UTF8.GetString($amp), "&");
                $currentTerms = $previousTerms + ",""" + $termName + """";
            
                $file.Writeline("`t" * $tabCount + "`t<term Name='" + $termName + "' isAvailableForTagging='" + $_.IsAvailableForTagging + "'>");
                $file.Writeline("`t" * $tabCount + "`t`t<description>" + $_.GetDescription() + "</description>");
            
                if ($level -lt 7) {
                    Export-SPTermSet $_.Terms ($level + 1) ($previousTerms + $currentTerms)
                }
                $file.Writeline("`t" * $tabCount + "`t</term>");
            }
        }
    }

    if ($terms.Count -gt 0)
    {
        $file.Writeline("`t" * $tabCount + "</terms>");
    }
}

try {
    Write-Host "Starting export of Metadata Termsets" -ForegroundColor Green
    $ErrorActionPreference = "Stop"
    Add-Snapin

    if (!($exportPath)) {
        $exportPath = (Get-ScriptDirectory)
    }

    Write-Host "Site: $siteUrl" -ForegroundColor Yellow
    Write-Host "Term Group: $termGroup" -ForegroundColor Yellow
    Write-Host "Export Path: $exportPath" -ForegroundColor Yellow

    Export-SPTerms $siteUrl $termGroup $exportPath
}
catch {
    Write-Host ""
    Write-Host "Error : " $Error[0] -ForegroundColor Red
    throw
}
finally {
    Remove-Snapin
}
Write-Host Finished -ForegroundColor Blue

  
How to import group to Term Store Management using PowerShell Script in SharePoint 2103

      The following PowerShell script can be used to import group to term store management. Here we have to give Service name , site Url , Path and Name of term Store.

##Variables to be edited##############
$MMSService="
servicename"
$CentralAdmin="
http://localhost"

$CSVFILEPATH= "C:\Group.csv"

##Variables that should not be edited
$groupname="Name_Of_Term_Store"

cls
Write-Host "Loading IIS module"
Write-Host "Loading SharePoint Commandlets"
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
Write-Host -ForegroundColor Green " Commandlets Loaded ... Loading Variables"
Write-Host
function ImportTermSet([Microsoft.SharePoint.Taxonomy.TermStore]$store, [string]$groupName, [PSCustomObject]$termSet) { 
  function ImportTerm([Microsoft.SharePoint.Taxonomy.Group]$group, 
                      [Microsoft.SharePoint.Taxonomy.TermSet]$set, 
                      [Microsoft.SharePoint.Taxonomy.Term]$parent, 
                      [string[]]$path) {       
    if ($path.Length -eq 0) {
      return
    } elseif ($group -eq $null) {
      $group = $store.Groups | where { $_.Name -eq $path[0] }
      if ($group -eq $null) {
        $group = $store.CreateGroup($path[0])
      }
    } elseif ($set -eq $null) {
      $set = $group.TermSets | where { $_.Name -eq $path[0] }
      if ($set -eq $null) {
        $set = $group.CreateTermSet($path[0])
      }
    } else {
      $node = if ($parent -eq $null) { $set } else { $parent }
      $parent = $node.Terms | where { $_.Name -eq $path[0] }      
      if ($parent -eq $null) {
        $parent = $node.CreateTerm($path[0], 1033)
      } 
    }
   
    ImportTerm $group $set $parent $path[1..($path.Length)]
        Commit $store 2>&1 | out-null
    #$store.CommitAll()
  }
  
  function RemoveTermGroup([Microsoft.SharePoint.Taxonomy.TermStore]$store, [string]$groupName) {
    $group = $store.Groups | where { $_.Name -eq $groupName }
    if ($group -ne $null) {
      $group.TermSets | foreach { $_.Delete() }
      $group.Delete()
      $store.CommitAll()
    }
  }
  
  function Commit($store) {
    $store.CommitAll()
  }  
  RemoveTermGroup $store $groupName
  $termSetName = $termSet[0]."Term Set Name"   
  $termSet | where { $_."Level 1 Term" -ne "" } | foreach {
    $path = @($groupName, $termSetName) + @(for ($i = 1; $i -le 7; $i++) { 
      $term = $_."Level $i Term"
        if ($term -eq "") {
          break
        } else {
          $term
        }
      }
    )       
    ImportTerm -path $path
    $ErrorActionPreference = "Continue";
  }
  }
$CAsite =$CentralAdmin
Sleep 2
"Connecting to Term Store"
Write-host
$session = new-object Microsoft.SharePoint.Taxonomy.TaxonomySession($CAsite)
$store = $session.TermStores[$MMSService]  
"Importing Term Set CSV File"
Write-Host
$termSet = Import-Csv $CSVFILEPATH
ImportTermSet $store $groupname $termSet
"All Term Sets have been imported"
Write-Host

The following image to show
 "service name"
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiV94GNyHUbtrF1jQVuywh_L1qq99fNmo0a8tOJYArtm2w1mWv5e1jzDa2QwCXRJW4qAXkxEhi4zkl1nZkLCah2HlcJ7mh1sEPrD79tFquNHl-W-KPovTdokUvGafd4OTJ6MVCC4hVu-S2G/s1600/0.png


How to create Lookup Field List using Power shell Script in SharePoint 2013

Continution to Previous post  , here we are going to see how to create lookup field from Power Shell  in SharePoint 2013

 Create a SharePoint Custom List Department with Lookup Column

SNAME    -  Lookup
SID -Number

#List type or template
$spTemplate = $spWeb.ListTemplates["Custom List"]

#Get all the lists to the listcollection
$spListCollection=$spWeb.Lists

#adding the new list to the list collection
$spListCollection.Add("Department","Department",$spTemplate)

#get the path of subsite and sitecollecion
$path = $spWeb.url.trim()

#get the list to the list object
$spList = $spWeb.GetList("$path/Lists/Department")

#adding the field type(Lookup) to the list
$LookupList= $spWeb.Lists["Student"]
$fieldXml='<Field Type="Lookup" DisplayName="SName" ShowField="SName" StaticName="SName" List="' + $LookupList.id + '" Name="SName"></Field>'
$spList.Fields.AddFieldAsXml($fieldXml,$true,[Microsoft.SharePoint.SPAddFieldOptions]::AddFieldToDefaultView)

#adding the field type(Number) to the list $spFieldType = [Microsoft.SharePoint.SPFieldType]::Number $spList.Fields.Add("SID",$spFieldType,$false) $Views = $spList.Views["All Items"] $Views.ViewFields.Add("SID") $Views.Update

How to create List using Power shell Script in SharePoint 2013
In this post we are going to see how to create Custom List from Power Shell in SharePoint 2013.

Create a SharePoint Custom List  Student Info with Columns
SNo    -  Number
SName  -  Text
Gender -  Choice
Photo  -  URL

#To which site u want to create the list
$spWeb=Get-SPWeb -Identity http://c4968397007

#List type or template
$spTemplate = $spWeb.ListTemplates["Custom List"]

#Get all the lists to the listcollection
$spListCollection=$spWeb.Lists

#adding the new list to the list collection
$spListCollection.Add("Studentlist","Studentlist",$spTemplate)

#get the path of subsite and sitecollecion
$path = $spWeb.url.trim()

#get the list to the list object
$spList = $spWeb.GetList("$path/Lists/Studentlist")
#adding the field type(Number) to the list
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Number
$spList.Fields.Add("SNo",$spFieldType,$false)

#adding the field type(Text) to the list
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Text
$spList.Fields.Add("SName",$spFieldType,$false)
#adding the field type(choice) to the list
$choices = New-Object System.Collections.Specialized.StringCollection
$choices.Add("Female")
$choices.Add("Male")
$spFieldType = [Microsoft.SharePoint.SPFieldType]::Choice
$spList.Fields.Add("Gender",$spFieldType,$false,$false,$choices)

#adding the field type(url) to the list
$spList.Fields.Add("Photo","URL",$false)
$Views = $spList.Views["All Items"]
$Views.ViewFields.Add("SNo")
$Views.ViewFields.Add("SName")
$Views.ViewFields.Add("Gender")
$Views.ViewFields.Add("Photo")
$Views.Update()

How to remove SPWebApplication using powershell script in SharePoint 2013


         Remove-SPWebApplication cmdlet deletes the Web application specified by the Identity and Zone parameters. If no zone is provided, the entire Web application and all zones are removed.

Remove particular zone:


  
  Get-SPWebApplication "http://sitename"|Remove-SPWebApplication -Zone "Intranet" -Confirm

    
Identity: http://sitename. 

             It removes the Internet zone Web application extension on the Web application at http://sitename. This command does not remove the content databases or the IIS Web site.

Remove Perticular web application content databases and IIS website :

    Remove-SPWebApplication http://sitename -Confirm -DeleteIISSite -RemoveContentDatabases

         It removes the Web application, all content databases, and the IIS Web site at
http://sitename
Delete App pool in Sharepoint Using PowerShell
How to remove unused Application Pool in SharePoint

There is only one way to remove the application pool for SharePoint, using powershell command.

First open the SharePoint 2013 management power shell as a administrator

Now we have to get the all application pools.

'Get-SPServiceApplicationPool'

Now we can able to see all Application Pools.

Get-SPServiceApplicationPool -Identity <Name of the application pool>

Now we can to delete what ever the application pool we want.

Remove-SPServiceApplicationPool 'Name of the Application Pool'
 Default is "Y">:Y

how to deploy wsp in sharepoint 2013 using powershell

how to deploy wsp in sharepoint 2013 using powershell

I kept the wsp file in my Desktop.

Now i opened the SharePoint Powershell run this script.
Add-SPSolution "C:\Users\DotNetSharePoint\Desktop\WSPName.wsp"
Adding wsp to solution Management
once we run this command on powershell we can see the wsp file in Central Admin->System Settings->Manage Form Solutions.
we can see the deployed WSP.

Deploy the Wsp to Particular web application

Install-SPSolution –Identity WSPName –WebApplication 
http://Test:1234/ –GACDeployment

Active the Feature 

Enable-SPFeature –Identity FeatureName –url 
http://Test:1234/sites/Home
Deactive the Feature

Disable-SPFeature –Identity FeatureName –url 
http://Test:1234/sites/Home
Uninstall the Feaure

Uninstall-SPFeature FeatureName

 How to send email using powershell in sharepoint
Here we can see the script,the way we can sent mail alerts using power shell

$EmailFrom = "FromEmail@domain.com"
$EmailTo = "ToEmail@domain.com"
$SMTPServer = "YourSmtpServerName"
$EmailSubject = "Enter your Subject you want"

$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($EmailFrom)
$mailmessage.To.add($EmailTo)
$mailmessage.Subject = $EmailSubject
$mailmessage.Body = "Email body"
#if we are sending any html body we have to use below line
$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer)
#if you want any network credentials set user name and password.
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password");
 
$SMTPClient.Send($mailmessage)
how to send email with attachment in powershell
$Body = "get the information here to show the data with attachement"  | Set-Content C:\somename.html

$file = "C:\somename.html"
$EmailFrom = "FromMail@Domain.com"
$EmailTo = "ToMail@Domain.com"
$SMTPServer = "Your Smtp Server Name"
$EmailSubject = "Enter Your Subject"
$att = new-object Net.Mail.Attachment($file)

#Send mail with attachment
$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($EmailFrom)
$mailmessage.To.add($EmailTo)
$mailmessage.Subject = $EmailSubject
$mailmessage.Body = $Body
$mailmessage.IsBodyHTML = $true
$mailmessage.Attachments.Add($att)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer)
$SMTPClient.Send($mailmessage)
$att.Dispose()

how to connect sqlserver using powershell
Here we can find the script the way we can connect sqlserver DB using PowerShell.

$con = New-Object System.Data.SqlClient.SqlConnection
$con.ConnectionString = "Server=servername;Database=databasename;User ID=username;Password=password;"
$con.Open()
$sql = "your select query"
$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$con)
$rdr = $cmd.ExecuteReader()
$test = @()
while($rdr.Read())
{
    $test += ($rdr["fieldname"].ToString())
}
#here we can see the output using

Write-Output $test
  

Activating and Deactivating Features in a SharePoint Site Collection Using Power Shell

If we want to know the list of features activated in your Site Collection
Run the following command in SharePoint 2013 Management shell
It will gives list of features with DisplayName,ID
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiT50Z6tYrVCQI1e6Th8fLmdeCBohHxSHoY8uQGxn0ZcaM0y2lwfASf6ylTKxb748NYiVGE1HPy-JmVesiF-He7OLvrNpjacxbcF7wdG4mqXdzZARobMMUzBTv6XA6FFOhd9ykh-I6H37AL/s1600/featurelist.png
For activating or deactivating  the feature use we can do based on Feature Name or Feature ID
Activating the Feature:
Enable-SPFeature –Identity FeatureIDhere –url  http://DotNetSharePoint:1234/sites/SharePoint
Or
Enable-SPFeature –Identity FeatureNamehere –url  http://DotNetSharePoint:1234/sites/SharePoint

Deactivating the Feature:
Disable-SPFeature –Identity FeatureIDhere –url  http://DotNetSharePoint:1234/sites/SharePoint
Or
Disable-SPFeature –Identity FeatureNamehere –url  http://DotNetSharePoint:1234/sites/SharePoint

How to Create a Site Collection using Power Shell

Using Power Shell we can create site collection easily, by using the below command.
How to delete list items using powershell
If you want to Delete the SharePoint list items,we can delete easily using the PowerShell.

(Get-SPWeb http://DotNetSharePoint:1234/sites/SharePoint).Lists["YourListName"].Items | % { $_.ParentList.GetItemById($_.ID).Delete() }

How to configure SharePoint Outgoing Email Settings using powershell
I prepared a script,easy way to configure the outgoing email using powershell.

Here we check the image before executing the script
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKyZdzdg7mTC7srdij_6WLnhY3peRpYam1iD_Ci8mceJuGbKKH5wEVUnpz6ZNXMQAfwjwUm9LyeLwYbn69uYkewrRNph2wbv5mmwOIi3jcuhwheZsCxLSAZt_SHweb5AT3GjfGcPOWX8-z/s1600/outgoingemail1.png


$SMTPServer = 'mail.dotnetsharepoint.com'
$FromAddress = 'jlakshmitulasi@dotnetsharepoint.com'
$ReplytoAddress = 'jlakshmitulasi@dotnetsharepoint.com'
$Charset = 65001

$CAWebApplication = Get-SPWebApplication -IncludeCentralAdministration | Where { $_.IsAdministrationWebApplication }
$CAWebApplication.UpdateMailSettings($SMTPServer, $FromAddress, $ReplytoAddress, $Charset)

Here we can check the output after executed the script
                            
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyPyYitvrS1YgdMlnFWeURU-y7767vNEQHsoaFoTrpUdJadRoYaqsXZQ8S1nMZjZJcsi8p4flKZ3oMj_VD_5QcVfMi2LziVJqUTTSqWSKQOTvUkudZeFVRTiMQvCgKxh2Cx1bZjl9sKWuu/s1600/outgoingemail2.png

How to download WSP file Central Admin
Some times we need to take the backup of WSP file,if you don't have back of the old WSP file
we can get it easily from central admin,before deploying the new WSP.

 using power shell run this below script.

$SPFarm = Get-SPFarm
$getWSP = $SPFarm.Solutions.Item(“dotnetsharepoint.wsp”).SolutionFile
$getWSP.SaveAs(“C:\dotnetsharepoint.wsp”)

How to download all wsp files from Central Admin

If you want to take the backup of all the wsp files from your central admin.

Use this Power shell Script.
$pathName = "c:\WSPFiles\"
foreach ($solution in Get-SPSolution)
   {

    $solid = $Solution.SolutionID
    $title = $Solution.Name
    $filename = $Solution.SolutionFile.Name
    $solution.SolutionFile.SaveAs("$pathName\$filename")
}

Copy Files between SharePoint Document Libraries Using Power Shell
      I am having a Site Collection, in that am having two document library’s, once library having files i want to copy the same files to move the another library.

Using the below power shell I implemented this.

Add-PsSnapin Microsoft.SharePoint.PowerShell
#Refereing the SiteCollection URL
$web = "http://dotnetsharepoint:1234/sites/sharepoint/"
#Refereing the Source DocumentLibray Having Files
$sourLibrary = (Get-SPWeb $web).Folders["SourceLibraryName"]
#Refereing the Destination of DocumentLibray to place Files
$destLibrary = (Get-SPWeb $web).Folders["DestinationLibraryName"]

$destFiles = $destLibrary.Files
foreach ($file in $sourLibrary.Files)
{
    $currentFile = $file.OpenBinary()
    $destURL = $destFiles.Folder.Url + "/" + $file.Name
    $destFiles.Add($destURL, $currentFile, $true)


How to create managed path in SharePoint using PowerShell

Using Power Shell we can create it easily
Open the SharePoint2013 Management Shell
Use the below commands to create and remove the managed path for Explicit and Wild
Creating the Managed Path Explicit
New-SPManagedPath -RelativeURL "my" -WebApplication "http://SharePoint:1234/" – Explicit
Creating the Managed Path Wild
New-SPManagedPath "personal" -WebApplication http://SharePoint:1234/
  
Remove Managed
Remove-SPManagedPath -Identity " personal "  -WebApplication "http://SharePoint2013:1234/" -confirm:$false 
If we want to get the all managed paths for that particular web application
Get-SPManagedPath  -WebApplication http://SharePoint2013:1234/
http://www.pluralsight.com/courses/using-windows-powershell-sharepoint-2010-2013


Powershell Tips and Tricks (and commandline)

Here are some of my favorite powershell tips and tricks (and some general commandline stuff too).
First, some pure command line stuff,
1. Find a file on your hard disk -       dir filename /s
2. Find a file on your hard disk without all the directory info goo -      dir filename /s/b
3. Create a list of files, say your MP3s to share with a friend? (disclaimer: don't do this piracy crap)    dir *.mp3 /b > filelist.txt
4. Find a directory -
      dir dirname /s /ad
5. Move between directories easily     C:\Documents and Settings\Sahil Malik>pushd .
     C:\Documents and Settings\Sahil Malik>cd \
     C:\>popd
     C:\Documents and Settings\Sahil Malik>
6. Hit Tab for directory/filename completion
7. Press F7 for a previous command list. User Cursor keys to select the command you need.
8. View all environment variablesSET
9. View only system variables that start with WSet W
10. View a particular env. variableECHO %WINDIR%
11. Find what process has opened what portnetstat –noa
12. Widen your command prompt.mode 120,100
13. View your TCP/IP settings.netsh interface ip show config
14. Weird looking colorscolor 8f
15. Find a string in a list of files, for example "Foo" in all .cs files in your project tree:findstr /i /s "foo" *.cs
(You might know that the windows search doggie does an awful job at search thru files, I think it just ignores files with recognized extensions, so .cs will be ignored YUK).
16. Refresh the netbios nametables:nbtstat –R
17. Get number of open client connections on a web front endGet-Counter -Counter 'web service(_total)\current connections' -ComputerName servername
18. Lost an application Pool password? No problem -
cmd.exe /c $env:windir\system32\inetsrv\appcmd.exe list apppool “SharePoint - 80" /text:ProcessModel.Password
And now for some Powershell stuff with some SharePoint influence
19. In SharePoint you see that Synch button? Causing you a heartache? You can kill it universally on a farm using this -
Get-SPSite -limit all | get-SPWeb -limit all | Foreach {$_.Title = $_.Title;
$_.ExcludeFromOfflineClient=1; $_.Update()}
20. PowerShell 3.0 grid stuff, you just have to try this,
$web = Get-SPWeb http://sp
$list = $web.Lists | Out-GridView -PassThru
21. Find files with matching text
ls -r | ?{$_ | Select-String -Pattern "texttosearch"}
22. Extract a WSP from SharePoint central administration as a file
$farm = Get-SPFarm
$farm.solutions.item(“solutioname.wsp”).SolutionFile.SaveAs(“c:\whateverfilenameandpath.wsp”)
23. A correlation ID giving you heartache on a multiple server farm? Merge it all up for just a single correlation ID with this -
Merge-SPLogFile –Path c:\whateverfile.log –Correlation <correlationID>
24. ULS Viewer is too damn slow for you? Find full error messages zippity zip fast
Get-SPLogEvent | Where {$_.Correlation -Eq "f463c19c-e41f-f09e-a2ef-b8a749edf422" } | ft Message
25. Blame your sysadmins when they screw up a installation
26. Accidentally deleted a site collection? No problem, you can restore it without resorting to database backups,
Get-SPDeletedSite (gives you the ID)
Restore-SPDeletedSite (restores it)
27. SharePoint isn’t great when it comes to database consistency. I like to say SharePoint and SQL Server are an arranged marriage where SQL Server is the abused bitch. You can find orphaned objects with this,
$cdb = get-SPContentDatabase
$cdb.Repair($false)
28. So you have an object, but what methods and properties does it support? Find out like this,
$web = Get-SPWeb http://sp
$web | Get-Member
29. Get some fresh air, check the weather outside,
Invoke-RestMethod -Uri "http://api.openweathermap.org/data/2.5/weather?q=Zagreb"
30. Got something work? And you’d like to save the commands used to get there? Just do this -
Get-History | Select –Expand CommandLine | Out-File script.ps1
31. Make your computer more fun,
iex (New-Object Net.WebClient).DownloadString(“http://bit.ly/e0Mw9w”)
32. And finally, have Powershell find you a new job,
stop-computer -force | Get-ADCOmputer -Filter *
 Backup and Restore using PowerShell;-



Back up farms:-
Backup-SPFarm -Directory <BackupFolder> -BackupMethod {Full | Differential} [-Verbose]

Restore farms:-
Restore-SPFarm -Directory <BackupFolder> -RestoreMethod Overwrite [-BackupId <GUID>]<Type the appropriate cmdlet, including parameters and values, and enclose the values for the parameters in "placeholder" tags >

Back up farm configurations:-
Backup-SPConfigurationDatabase -Directory <BackupFolder> -DatabaseServer <DatabaseServerName> -DatabaseName <DatabaseName> -DatabaseCredentials <WindowsPowerShellCredentialObject> [-Verbose]

Restore farm:-
Restore-SPFarm -Directory <RestoreShare> -RestoreMethod Overwrite -ConfigurationOnly

Back up web applications:-
Backup-SPFarm -Directory <BackupFolder> -BackupMethod {Full | Differential} -Item <WebApplicationName> [-Verbose]

Restore web applications:-
Restore-SPFarm -Directory <BackupFolderName> -RestoreMethod Overwrite -Item  <WebApplicationName> [-BackupId <GUID>] [-Verbose]

Back up service applications:-
Backup-SPFarm -Directory <BackupFolder> -BackupMethod {Full | Differential} -Item <ServiceApplicationName> [-Verbose]

Restore service applications:-
Restore-SPFarm –Directory <BackupFolder>  -Item " <ServiceApplicationName> "
-RestoreMethod Overwrite [-BackupId <GUID>] [-Verbose]

To restore all the service applications, at the Windows PowerShell command prompt, type the following command:
Restore-SPFarm -Directory <BackupFolder>  -Item "Farm\Shared Service Applications"
-RestoreMethod Overwrite [-BackupId <GUID>] [-Verbose]

Back up User Profile service applications:-
Backup-SPFarm -Directory <BackupFolder> -BackupMethod Full -Item Farm\Shared Services\Shared Service Applications\<ServiceApplicationName> [-Verbose]

Restore a User Profile Service service application:-
Restore-SPFarm -Directory <BackupFolder> -Item Shared Services\Shared Services Applications\<ServiceApplicationName> -RecoveryMethod Overwrite [-BackupId <GUID>] [-Verbose]

Back up Search service applications:-
Backup-SPFarm -Directory <BackupFolder> -BackupMethod {Full | Differential} -Item “<SearchServiceApplicationName>” [-Verbose]

Restore Search service applications:-
Restore-SPFarm -Directory <BackupFolder> -Item "<ServiceApplicationName>" -RecoveryMethod Overwrite [-BackupId <GUID>] [-Verbose]

When you restore a Search service application, it is automatically paused. To resume the Search service application when the restore has completed, type the following command:

$ssa = Get-SPEnterpriseSearchServiceApplication <SearchServiceApplicationName>
$ssa.ForceResume($ssa.IsPaused())

Back up the Secure Store Service:-
Backup-SPFarm -Directory  <BackupFolder> -BackupMethod Full -Item <SecureStoreService > [-Verbose]

Restore Secure Store Service:-
Restore-SPFarm -Directory <BackupFolder> -Item <SecureStoreServicename> -RecoveryMethod Overwrite [-BackupId <GUID>] [-Verbose]

After the restore operation has successfully completed, you must refresh the passphrase. At the Windows PowerShell command prompt, type the following command:

Update-SPSecureStoreApplicationServerKey -Passphrase <Passphrase>

Back up content databases:-
Backup-SPFarm -Directory   <BackupFolder>  -BackupMethod {Full | Differential} -Item <ContentDatabaseName> [-Verbose]

Restore content databases:-
Restore-SPFarm -Directory <BackupFolder> -RestoreMethod Overwrite -Item <ContentDatabase> [-BackupId <GUID>] [-Verbose]

Attach and restore a read-only content database:-
Attaching a content database by using the Mount-SPContentDatabase cmdlet differs from attaching a database in SQL Server by using SQL Server tools. Mount-SPContentDatabase associates the content database with a Web application so that the contents can be read.

Mount-SPContentDatabase -Name <DatabaseName> -WebApplication <WebApplicationID> [-Verbose]

Restore content from unattached content databases:-
You can restore or copy content, such as sites, site collections, lists, or document libraries, from a content database without having to attach the content database to the farm.

Get-SPContentDatabase -ConnectAsUnattachedDatabase  -DatabaseName <DatabaseName> -DatabaseServer <DatabaseServer>

Back up databases to snapshots :-
CREATE DATABASE <snapshot name>
ON
(
NAME=<logical name of the database file>,
FILENAME = 'c:\WSS_Backup1.ss')
AS SNAPSHOT OF <database name>;

Back up solution packages:-
Backup-SPFarm -backupmethod full -directory <UNC location> -item "farm\solutions"
Here: 1. <UNC location> is the UNC location of the directory that you want to back up to.
          2. To back up a single solution, add the name of the solution to the item path "farm\solutions"
Back up site collections:-
Backup-SPSite -Identity <SiteCollectionGUIDorURL> -Path <BackupFile> [-Force] [-NoSiteLock] [-UseSqlSnapshot] [-Verbose]

Get-SPSite | format-list -property id,url

Restore customizations:-
Restore-SPFarm -Directory <BackupFolder> -RestoreMethod Overwrite -BackupId <GUID> -Item <SolutionPath>

Restore site collections:-
Restore-SPSite -Identity <SiteCollectionURL> -Path <Backup file> [-DatabaseServer <DatabaseServerName>] [-DatabaseName <ContentDatabaseName>] [-HostHeader <Host header>] [-Force] [-GradualDelete] [-Verbose]

Back up apps:-
The app for SharePoint content and packages are in the SharePoint 2013 content databases in individual site collections. All app for SharePoint license and security data is stored in the App Management Service and the Secure Store Service application databases. Additional app for SharePoint data is stored in the SharePoint 2013 configuration database, in the form of Internet Information Services (IIS) web sites or web applications, and Web Part packages. You must back up the following SharePoint 2013 databases at the same time:
·         Content
·         Configuration
·         Secure Store Service application
·         App Management service application
If you have to eventually restore the databases, you have to restore the same version of each database that you backed up. In other words, don't restore a content database that's six months older than the configuration database.

Restore apps:-
The apps for SharePoint can reference the following SharePoint 2013 databases which you may have to restore. You should also restore the site collection where the app for SharePoint is located if you are restoring the apps for SharePoint to the same environment.
·         Content
·         Configuration
·         Secure Store Service application
·         App Management service application

Restore-SPSite -Identity <SiteCollectionURL> -Path <Backup file> [-DatabaseServer <DatabaseServerName>] [-DatabaseName <ContentDatabaseName>] [-HostHeader <Host header>] [-Force] [-GradualDelete] [-Verbose]

Export sites, lists, or document libraries:-
Export-SPWeb -Identity <SiteURL> -Path <Path and File Name> [-ItemUrl <URL of Site, List, or Library>] [-IncludeUserSecurity] [-IncludeVersions] [-NoFileCompression] [-GradualDelete] [-Verbose]

Import a list or document library:-

Import-SPWeb -Identity  <SiteURL>  -Path <ExportFileName>  [-Force] [-NoFileCompression] [-Verbose]





No comments:

Post a Comment