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

Powershell to get Property bag for Farm, Web App or Site Collection

Application developers, now a days store many of the configurable properties in the Property bags. As an administrator you might frequently be asked the value of these properties.

I  used below scripts to check Properties at Farm, Web Application and Site Collection level.

#Add PS SnapIn for SharePoint

# Get all the Properties from Farm Property bag
$myFarm = Get-SPFarm;

foreach ($prop in $myFarm.Properties.GetEnumerator() | Sort-Object -Property Name) {
                     Write-Host " - " $prop.Name "->" $prop.Value
}

# Get all the Properties from Web Application Property bag
$myWebApp = Get-SPWebApplication "http://webapp"

foreach ($prop in $myWebApp.Properties.GetEnumerator() | Sort-Object -Property Name) {
                     Write-Host " - " $prop.Name "->" $prop.Value
}

# Get all the Properties from Site Collection Property bag
$myWeb = Get-SPWeb "http://sitecollection"

foreach ($prop in $myWeb.Properties.GetEnumerator() | Sort-Object -Property Name) {
                     Write-Host " - " $prop.Name "->" $prop.Value
}


Create SharePoint user profiles using powershell

I have been recently asked to create thousands of user profiles in our test environment.

Ideally importing profiles from AD or provisioning the profiles is advisable, but due to nature of our test environment it was not possible. After searching a bit, I found a script and modified it for this purpose. The script requires all the profile related data to be stored in a CSV.

#Add-PSSnapin if not added already using this link 

$portalsite = "http://spportal"
$portalcontext = Get-SPServiceContext -Site $portalsite


$upm = New-Object -TypeName Microsoft.Office.Server.UserProfiles.UserProfileManager -ArgumentList $portalcontext
$userslist = Import-Csv -Path "userprofilelist.csv"

#Loop through all the rows of csv

for($count=0; $count -lt $userslist.Count; $count++)
{

#Create new User Profile
$upm.CreateUserProfile($userslist[$count].UserName)
$profileproperty = $upm.GetUserProfile($userslist[$count].UserName)

#Custom User Profile being updated for the user
$profileproperty["property1"].Value = $userslist[$count].Property1
$profileproperty["property2"].Value = $userslist[$count].Property2
$profileproperty["property3"].Value = $userslist[$count].Property3
$profileproperty.Commit()

}

Hope this helps. Please see my other scripts to export the data to CSV.

Find Orphaned SharePoint Items using PowerShell script

The script below helps you find the orphaned items from SharePoint content databases

if ((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{Add-PSSnapin Microsoft.SharePoint.Powershell}


$CntDBs = Get-SPContentDatabase

ForEach ($CntDB in $CntDBs)
{   

      Write-Host "Detecting Orphans for " $CntDB.Name    $CntDB.Repair($false)
}


The above script will only list down the Orphaned items. You  can also repair these by changing

$CntDB.Repair($false) to $CntDB.Repair($true)

However before doing any such repair, you should be taking a back up of your DB.

Powershell scripts to Extract, import and deploy SharePoint farm solutions

When you are maintaining SharePoint Farm, you might often want to be able to extract all SharePoint solution in the farm, import it back and deploy it.

I have seen such requirements during the migration, creation or maintenance of various environments like Pre-Prod, production etc.
After searching it on Internet, here are the 3 powershell scripts I have found:

Extract all the farm solutions:

(Get-SPFarm).Solutions | ForEach-Object{$var = "C:\<LocationUWantToStoreWSP>\" + $_.Name; $_.SolutionFile.SaveAs($var)}

 
Import all the farm solutions:

Get-ChildItem | ForEach-Object{Add-SPSolution -LiteralPath $_.Fullname}

Deploy all solutions to farm:

Get-SPSolution | ForEach-Object {If ($_.ContainsWebApplicationResource -eq $False) {Install-SPSolution -Identity $_ -GACDeployment} else {Install-SPSolution -Identity $_ -AllWebApplications -GACDeployment}}



 





 

Get log details using Merge-SPLogFile CMDlet

As you encounter any error/issue with your SharePoint estate, you want to know root cause of the error. You might have the correlation ID of the error or some other basic information like start time, end time etc.

You can open ULS Viewer but  it is very tedious to go through the logs and find out the cause of any issue.

With PowerShell, you can reduce the effort by using the Merge-SPLogFile CMDlet. The script given below merges the log files for specific correlation ID and start time.

Add-PSSnapin Microsoft.SharePoint.PowerShell
    
Merge-SPLogFile -Path "<path where you want to store merged log>" -Correlation "<Correlation ID>" -Overwrite -StartTime '02/01/2014 11:00:00'




There are many other parameters configurable for this CMDlet. Using Start time and end time parameters you can increase the performance.

More examples are provided at :
http://technet.microsoft.com/en-us/library/ff607721(v=office.14).aspx


 

Adding SharePoint Snap-in for Powershell -

When you want to use Sharepoint CMDlets in Powershell, you need to add SharePoint Snap-In using the following CMDlets:

Add-PSSnapin "Microsoft.SharePoint.PowerShell"

If you don't add the snap in, your CMDlet command will not be recognized.

Adding snap-in for every script or Powershell window is irritating task. You can also add all the snap-in permanently to all PowerShell window using the method given in below articles.

http://blogs.msdn.com/b/kaevans/archive/2011/11/14/add-microsoft-sharepoint-powershell-snap-in-to-all-powershell-windows.aspx

Restore deleted site collections in SharePoint 2010

If users have deleted document, lists or sites they can restore it from site recycle bins. In case they are not found in site recycle bin, Site collection admins can restore it from Site collection recycle bins.

However what should we do if the whole site collection is deleted? In older world, you would have to restore the complete content database to a separate environment. But in SharePoint 2010 and 2013, you have got another option.

At farm level, deleted site collections are stored in SPdeletedsite object. You can find a list of all deleted sites using following powershell script:

Get-SPDeletedSite - This will list all the deleted site collections as below


If your site is present in this list, you can restore it using the below CMDlet

Restore-SPDeletedSite -Identity /sites/HSCel

You will be asked to confirm this action before you complete it.




Please note that you have to use the relative path of the site.

In case multiple sites with same name, use site ID for deletion

If you want to remove a site collection permanently from your farm use the following:

Remove-SPDeletedSite -Identity /sites/HSCel
To explore other features of these CMDlets, please use following links:
http://technet.microsoft.com/en-us/library/hh286316.aspx
http://technet.microsoft.com/en-us/library/hh286319.aspx
http://technet.microsoft.com/en-us/library/hh286317.aspx

Powershell to add SWF mime type

To avoid getting download prompt while opening an SWF file, you can add SWF MIME type to your web application. This will make sure that your SWF file opens in the browser, even if Browser file handling for the web applicaiton is set to "Strict".

$app = Get-SPWebApplication http://<yourWebApp>

$app.AllowedInlineDownloadedMimeTypes.Add("application/x-shockwave-flash")

$app.Update()

You can change the 2 line of the script to use it for other file/MIME types.

To learn more about browser file handling, please visit this page.

Powershell script to change Browser File handling property

The following Powershell script modifies the browser file handling property of a web application to Permissive. You can change the script the change the property to Strict by modifying line 6:

$webApp = Get-SPWeb "http://<YourWebApplication>
#Find your document library
$docLibrary = $webApp.lists["Doc Lib Title"]

$docLibrary | Get-Member

#Change the Browser File handling property
$docLibrary.BrowserFileHandling = "Permissive"
$docLibrary.Update()



To learn more about browser file handling, visit this page.

Powershell script to list the Site Collection Quotas templates


One of my users asked me to provide a list of all the Site Quota
template limits. This was to be used by him to plan the sites.
I created the below function in Powershell to update the Site
Collection Quota template limits in a SharePoint list. . So here is a
copy of the powershell script and what it does:

1. Reads the Site Collection Quota templates for a web application
2. Updates the list of Quota templates to a SharePoint list
3. Update the status of activity in a status list

Powershell script function


function syncQuotaDetails([string] $webApp,[string] $listName,[string]
$statusListName)
{
try
{
$contentService =
[Microsoft.SharePoint.Administration.SPWebService]::ContentService
$quotaTemplates = $contentService.QuotaTemplates
$spAssignment = Start-SPAssignment
$myList = (Get-SPWeb -Identity $TSAdmin -AssignmentCollection
$spAssignment).Lists[$listName]
$listItems = $myList.Items
$listItemCount = $listItems.Count
for($x = $listItemCount - 1;$x -ge 0;$x--)
{
$listItems[$x].Delete()
}
$countQuotas = 0
foreach($quotaTemplate in $quotaTemplates)
{
if($quotaTemplate.Name -ne "" -and $quotaTemplate.Name -ne "Personal site")
{
$newItem = $myList.Items.Add()
$newItem["QuotaTemplateName"] = $quotaTemplate.name
$countQuotas = $countQuotas + 1
$newItem["QuotaTemplateID"] = $countQuotas;
$newItem["QuotaTemplateStorage"] =
($quotaTemplate.StorageMaximumLevel/1024)/1024
$newItem.Update()
}
}
Stop-SPAssignment $spAssignment

$spAssignment = Start-SPAssignment
$myList = (Get-SPWeb -Identity $TSAdmin -AssignmentCollection
$spAssignment).Lists[$statusListName]
$newItem = $myList.Items.Add()
$newItem["Activity"] = "Synchronise Tiers"
$newItem["Status"] = "Successful";
$newItem["Comment"] = "All Tier Quotas updated"
$newItem.Update()
Stop-SPAssignment $spAssignment
}
catch [Exception]
{
$managedPaths = get-spmanagedpath -webapplication $webApp
$spAssignment = Start-SPAssignment
$myList = (Get-SPWeb -Identity $TSAdmin -AssignmentCollection
$spAssignment).Lists[$statusListName]
$newItem = $myList.Items.Add()
$newItem["Activity"] = "Synchronise Tiers"
$newItem["Status"] = "Failed";
$newItem["Comment"] = $_.Exception.ToString();
$newItem.Update()
Stop-SPAssignment $spAssignment

}
}

The “QuotaTemplate” list where the above function will store data
should have 2 columns:

1. QuotaTemplateName – Single line of text
2. QuotaTemplateID – Number
3. QuotaTemplateStorage - Number

Similarly the status list where the status of the activity will be
stored should have following column:

1. Activity name – single line of text
2. Status – single line of text
3. Comment – Multiple line of text

Powershell script to list the managed paths


Recently I came across task to create a list of all the managed paths
for a SharePoint webapp and store it in a list. So here is a copy of
the Powershell script and what it does:

1. Reads the managed paths for a web application
2. Updates the list of managed path to a SharePoint list
3. Update the status of activity in a status list

Powershell script function


function syncManagedPaths([string] $webApp,[string] $listName,[string] $statusListName)
{
try
{
$managedPaths = get-spmanagedpath -webapplication $webApp
$spAssignment = Start-SPAssignment
$myList = (Get-SPWeb -Identity $TSAdmin -AssignmentCollection
$spAssignment).Lists[$listName]
$listItems = $myList.Items
$listItemCount = $listItems.Count
for($x = $listItemCount - 1;$x -ge 0;$x--)
{
$listItems[$x].Delete()
}
$countPaths = 0
foreach($managedpath in $managedpaths)
{
if($managedpath.Name -ne "" -and $managedpath.Name -ne "sites")
{
$newItem = $myList.Items.Add()
$newItem["Category"] = $managedpath.name
$countPaths = $countPaths + 1
$newItem["CategoryID"] = $countPaths;
$newItem.Update()
}
}
Stop-SPAssignment $spAssignment
$spAssignment = Start-SPAssignment
$myList = (Get-SPWeb -Identity $TSAdmin -AssignmentCollection
$spAssignment).Lists[$statusListName]
$newItem = $myList.Items.Add()
$newItem["Activity"] = "List managed paths"
$newItem["Status"] = "Successful";
$newItem["Comment"] = "All managed paths updated"
$newItem.Update()
Stop-SPAssignment $spAssignment
}
catch [Exception]
{
$managedPaths = get-spmanagedpath -webapplication $webApp
$spAssignment = Start-SPAssignment
$myList = (Get-SPWeb -Identity $TSAdmin -AssignmentCollection
$spAssignment).Lists[$statusListName]
$newItem = $myList.Items.Add()
$newItem["Activity"] = "Synchronise Category/Managed Paths"
$newItem["Status"] = "Failed";
$newItem["Comment"] = $_.Exception.ToString();
$newItem.Update()
Stop-SPAssignment $spAssignment
}
}

The “Managed path” list where the above function will store data
should have 2 columns:

1. Catergory – Single line of text
2. CategoryID - Number

Similarly the status list where the status of the activity will be
stored should have following column:

1. Activity name – single line of text
2. Status – single line of text
3. Comment – Multiple line of text

Logging in PowerShell Script

As in any development, logging plays a very important role, especially when it comes to debugging. And if you have just started using PowerShell script you will appreciate how important it is to log activities and results of the Powershell cmdlets you are running..

Here is basic code which helps you to log all the activities and their results.

Define the log file details – This part defines the file name and file path for the logging. For the log file you can choose any name. I| have chosen to assign the date variable as file name. If your script is running more than once a day, you can add hours,minutes and second variable also to make the file name unique.

$FilePath = "C:\Users\powershelluser\Documents\scripts\Log"
$FileName = Get-Date -Format yyyy-MM-dd
$File = "$FilePath\$FileName.txt"


Create a folder – This part creates a folder at the location given in the $FilePath variable if the filepath does not exist already.

if ((Test-Path -Path $FilePath) -ne $True)
{New-Item $FilePath -type directory}


Start logging – This part starts logging the details in the file mentioned above. You can start writing your script logic after this

Start-Transcript -Path $File –Force

Stop logging

Stop-Transcript