PowerShell Scripts

       To take the backup of a site collections

Backup-SPSite -Identity “SiteCollectionName -Path “Pathname\filename.bak”

To restore the site collections

Restore-SPSite -Identity “SiteCollectionName to be restored” -path “Pathname/filename.bak”

To restore the site collection under a hostheader webapplication

Restore-SPSite -Identity “SiteCollectionName to be restored” -Path “Pathname/filename.bak” -HostHeaderWebApplication “WebapplicationName”

To add the solution(.wsp) file to farm solutions

Add-SPSolution “WSPfilename”

To remove the solution(.wsp) file from the farm solutions

Remove-SPSolution -identity “WSPFilename”

To install the solution

Install-SPSolution -identity “WSPFilename” -Webapplication “Webapplicationname”        -GACDeployment

To uninstall the solution

Uninstall-SPSolution -identity “WSPFilename” -Webapplication “Webappliationname”

To install the feature

Install-SPFeature “FeatureName”

To Uninstall the feature

Uninstall-SPFeature “FeatureName”

To Enable the installed feature

 Enable-SPFeature -Identity “FeatureName/GUID”  -url “Webapp/SitecollectionName”

To Disable the feature

Disable-SPFeature -Identity “FeatureName/GUID”  -url “Webapp/SitecollectionName”

To attach the database

Mount-SPContentDatabase "DatabaseName" -DatabaseServer "DatabaseServerName" -WebApplication “WebapplicationName”
Note:-
The Mount-SPContentDatabase cmdlet attaches an existing content database to the farm. If the database being mounted requires an upgrade, this cmdlet will cause the database to be upgraded.
The default behavior of this cmdlet causes an upgrade of the schema of the database and initiates upgraded builds for all site collections within the specified content database if required. To prevent initiation of upgraded builds of site collections, use the NoB2BSiteUpgrade parameter. This cmdlet does not trigger version-to-version upgrade of any site collections.

To detach the database

Dismount-SPContentDatabase “DatabaseName”

To Export the web/list/library
Export-SPWeb -Identity "sitename" -path path.bak -itemURL "/sites/sitename/Lists/listname/" -IncludeUserSecurity -Includeversions all

To Import the web/list/library

Import-SPWeb -identity Url  -path pathname


To Test a content database

Test-SPContentDatabase -name “DatabaseName” -webapplication “WebapplicationName”

Note:-
Use the Test-SPContentDatabase cmdlet to test a content database against a Web application to verify all customizations referenced within the content database are also installed in the web application. This cmdlet can be issued against a content database currently attached to the farm, or a content database that is not connected to the farm. It can be used to test content databases from SharePoint 2010 Products and from SharePoint Products and Technologies.

To revert the visual upgrade to 2007 look and feel

$web = Get-SPWeb “SiteCollection/SiteName”
$web.UIVersion = 3
$web.UIVersionConfigurationEnabled = 1
$web.Update()

To complete the visual upgrade to 2010 look and feel

$web = Get-SPWeb “SiteCollection/SiteName”
$web.UIVersion = 4
$web.UIVersionConfigurationEnabled = 0
$web.Update()

To remove the threshold limit for a list/library

$web = Get-SPWeb “SiteCollection/SiteName”
$list = $web.Lists[“List/LibrayName”]
$list.enablethrottling = $false
$list.update()
$web.dispose()

To apply the threshold limit for a list/library

$web = Get-SPWeb “SiteCollection/SiteName”
$list = $web.Lists[“List/LibrayName”]
$list.enablethrottling = $true
$list.update()
$web.dispose()

To check if the threshold is removed or not for a list/library

$web = Get-SPWeb “SiteCollection/SiteName”
$list = $web.Lists[“List/LibrayName”]
Write-host $list.enablethrottling
$web.dispose()

To get all the subsites and its author(createdby),createddate for subsites in the site collection

$allsite=get-spsite “SiteCollectionName”
$allsite|get-spweb -limit all|foreach-object{Write-host $_.url, $_.author, $_.created}
$allsite.dispose()

To get the alert url for where it has been set.

Get-SPweb  “SiteCollection/SiteName” -limit all | ForEach-Object {$_.alerts|foreach-object{write-host $_.user, $_.properties["siteUrl"],$_.properties["dispformurl"]}}

To update the alert url. Suppose after migration, we found that the alert is pointing to old site.

Get-SPweb “SiteName” -limit all |ForEach-Object {$_.alerts|foreach-object{$_.properties["siteUrl"] = "NewSiteName to be updated";$_.update()}}

To get the Site title and url and description of a webapplication

Get-SPWebApplication "WebappliationName"|Get-SPSite -limit ALL|Get-SPWeb -limit ALL|Select-Object Title,Url,description

To get the all the sites title and url and description from under One site collection

Get-SPSite "SiteCollectionName" | Get-SPweb -limit all | select-object Title,Url,description


Commands to get all the versions for a document library in a site

$spweb=get-spweb “SiteName”
$list=$spweb.Lists["DocumentLibraryName"]
$itemscoll=$list.Items
foreach ($item in $itemscoll){foreach($ver in $item.versions){"Version : " + $ver.versionlabel + "     url : " + $item.url}}
$spweb.dispose()

To get the site primary and secondary admin of a site collection

$spsite=Get-SPSite "SiteCollectionName"
write-host $spsite.owner.userlogin,$spsite.secondarycontact.userlogin
$spsite.dispose()

Commands to check if the subsites are inheriting the permissions from its parent or not

Get-SPSite “SiteCollectionName” | Get-SPWeb -limit all | ForEach-Object {if ($_.HasUniqueRoleAssignments) {$_.url + ",Unique permissions"} else{$_.url + ",Inheriting from parent"}}

Note : We need to save the command in .ps1 format and send the output to .csv file.

Command to check in file when user has checked out and left company

$spWeb = Get-SPWeb “SiteName”
$getFolder = $spWeb.GetFolder(“Librayname/Foldername if any”)
$getFolder.Files | Where {$_.name -match "FileNamewithoutextn"} |
ForEach{
           $_.CheckIn(“Checked In By Administrator”)
       }
     $spWeb.Dispose()

Command to create the default groups(Owners, Members, Visistors) in the site

$web = get-spweb “SiteCollectionName/SiteName”
$owneralias = $web.ownerlogin
$secondaryowneralias = $web.secondaryownerlogin
$web.createdefaultassociatedgroups($owneralias,$secondaryowneralias,"")
$web.dispose()

Commands to get the all group names from the site and store it in .csv file

$site=Get-SPWeb “SiteCollectionName”
$groups=$site.sitegroups
foreach($grp in $groups){$grp.name | Out-File -FilePath E:\WorkDir\Groups.csv -append}
$site.dispose()

Command to delete the groups by taking the group name from the Csv file.

$web=Get-SPWeb "SiteCollectionName"
$groups=Import-csv E:\WorkDir\Groups.csv
foreach($_.delgroup in $groups)
{
            $web.SiteGroups.Remove($_.delgroup)
            $_.delgroup + " deleted successfully" | Out-File -FilePath E:\WorkDir\Output.csv -append
}
$web.dispose()

Delete a persistent column from a SharePoint List

$web = Get-SPWeb (Your site URL)
$list = $web.Lists[(Your List Name)]
$field = $list.Fields[(Your Column Name)]
$field.AllowDeletion = “true”
$field.Sealed = “false”
$field.Delete()
$list.Update()

$web.Dispose()

Update site author name

$web = get-spweb http://Your-Site
 $newAuthor = $web.EnsureUser("NewAuthor_LoginName")
 $web.Author = $newAuthor
$web.Update()

Get the size of a site

Get-SPSite sitename | select url, @{label="Size in MB";Expression={$_.usage.storage/1 MB}}

To test if the Visual upgrade successful

Get-SPSite "
sitename" | get-spweb -limit all | foreach-object{write-host $_.url, $_.uiversion}

Verbose enable and disable

Set-SPLogLevel -TraceSeverity Verbose (enable)

Set-SPLogLevel -TraceSeverity Unexpected

To create a new log file

Get-sploglevel

To reset a log level

Clear-SpLogLevel

To get the contentdatabase of a site

Get-SPContentDatabase -Site sitename

To get sites of a particular contentdatabase

Get-spsite  -contentdatabse <> -limit all

To delete from recycle bin

$url = “http://YourWebApp/ManagedPath/SiteName“;
$siteCollection = New-Object Microsoft.SharePoint.SPSite($url);
$siteCollection.RecycleBin.Count;
$siteCollection.RecycleBin.DeleteAll();
$siteCollection.Dispose();

To get size of a document library

$site = Get-SPWeb "sitename"
foreach ($list in $site.Lists)
{
if($list.Title -eq "Shared Documents")
{
                      $listSize = 0            
foreach ($item in $list.items)
{
                        $listSize += ($item.file).length
}
write-host "Library Name: " + $list.Title + ", Size: " + [ Math]::Round(($listSize/1KB),2) + "KB"
}
 }
$site.dispose()

To delete a list of sites

$data = get-content c:\path.txt
$count = $data.count
write-host Total Count: $count
$i = 0
foreach($url in $data)
{
$site = get-spsite $url
    $i = $i+1
    write-host Deleting Site No. $i `tURL: $site.url
Remove-SPSite -Identity $site.URL -Confirm:$False
    $site.url + "`tDeleted Site!!" | Out-File -FilePath "c:\path.csv" -Append
}
#write-host Site Not Found!!

Stop SharePoint timer service
net stop “SPTimerV4″

Start SharePoint timer service
net start “SPTimerV4

To Start a particular timer job (e.g. : immediate alerts)

$alertTimerJobGuids = Get-SPTimerJob | Where-Object{$_.name -eq "job-immediate-alerts"}
$alertTimerJobGuids | ForEach-Object {Start-SPTimerJob $_.Id}


To Merge ULS log file base on error message and correlation Id
Message : Merge-SPLogFile -Path “E:\Logfiles\ULS\MergeLogs20Aug4to7AM.log” -Overwrite -Message "*List does not exist*" -StartTime "08/20/2013 04:00" -EndTime "08/20/2013 07:00

Correlation : Merge-SPLogFile -Path “E:\Logfiles\ULS\MergeLogs28Oct5to6AM.log” -Overwrite -correlation "b08578b1-f459-4df4-bfb1-5d0eab4e05d7" -StartTime "10/28/2013 05:00" -EndTime "10/28/2013 06:00"

To remove all the existing versions of the documents except latest one.

get-spWeb “your site”
ForEach-Object {ForEach($_.list in $_.Lists)
{If($_.EnableVersioning -eq $True)
{
if($_.Title -eq "Shared Documents")
{
Write-host "List:"$_.Title "- List ID"$_.Id;
$_.MajorVersionLimit = 1;
$_.Update();

ForEach($_.item in $_.items)
{
$_.item.URL;$_.update()
}}}}}

To Lock or unlock site
Syntax:
Set-SPSite -Identity "<SiteCollection>" -LockState "<State>"
Where:
·         <SiteCollection> is the URL of the site collection that you want to lock or unlock.
·         <State> is one of the following values:
o Unlock to unlock the site collection and make it available to users.
o NoAdditions to prevent users from adding new content to the site collection. Updates and deletions are still allowed.
o ReadOnly to prevent users from adding, updating, or deleting content.
o NoAccess to prevent users from accessing the site collection and its content. Users who attempt to access the site receive an error message.






No comments:

Post a Comment