Saturday, July 30, 2016

Mask or hide created/modified user name from SharePoint list item forms and views using PowerShell

Short and sweet this one. As you probably know, whenever you view a list item in SharePoint, the display form shows the date and time that the item was created and last modified along with the name of the user that performed those operations. An example is shown in the screenshot below:

There may be occasions where the user name should be hidden from view for security or other purposes. This feature is normally used by SharePoint for the “Show user names in survey results” option on surveys, but it can be applied to any other list or document library by setting the ShowUser property of a list to false using the small PowerShell script below:




#Get Web and List objects
$web = Get-SPWeb http://SiteUrl
$list = $web.Lists["List Name"]

#Disable user from appearing in item dialogs
$list.ShowUser = $false
$list.Update()

#Dispose of Web object
$web.Dispose()

Once this script has been run on a list, the item display form looks like this:


Note that this also affects the Modified By and Created By columns in list views:



To restore the user name on the list form again, simply set the ShowUser property back to true.

Hide Title column from a SharePoint list using PowerShell

There are a number of times where you may not want the Title column to appear in a list. It is not recommended to delete the Title column, but the following PowerShell script hides it from view in the View and Edit Item pages and also the List Settings page. Note: You will still need to remove it from all list views.

#Get web object
$web = Get-SPWeb -identity "http://portal/testsite"

#Get list and Title column
$list = $web.Lists["TestList"]
$titleColumn = $list.Fields["Title"]

#Set Title to optional and hidden
$titleColumn.Required = $false
$titleColumn.Hidden = $true

#Update Title column and list
$titleColumn.Update()
$list.Update()

#Dispose of Web object
$web.Dispose()

Use PowerShell to check for illegal characters before uploading multiple files into SharePoint

If you have done any sort of bulk file uploading into SharePoint, you will be aware of issues with file names containing illegal characters. These files can disrupt the uploading process, potentially causing many hours of frustrating and time consuming tasks examining and repairing file names.

Files and folders are blocked by SharePoint during the uploading process for the following reasons:

  • They contain the following characters: & { } ~ # % (there are other illegal characters too, but as they are also blocked from use in Windows Explorer, it is assumed you will not have files named with these characters in your file system – if you do, you can adapt the script accordingly)
  • They are 128 characters in length or over
  • They start with a period character
  • They end with a period character
  • They contain consecutive period characters

The PowerShell script in this article allows you to scan an entire folder structure, including subfolders, and report on all files and folders containing one or more of the conditions listed above. There are also options within the script to automatically rename illegal characters in file names with something acceptable to SharePoint – for example, renaming the & symbol with the word ‘and’.

To use the script, first load the following function in a PowerShell console. Note that loading the function will not actually do anything until you call it later from the command line:

function Check-IllegalCharacters ($Path, [switch]$Fix, [switch]$Verbose)
{
    Write-Host Checking files in $Path, please wait...
    #Get all files and folders under the path specified
    $items = Get-ChildItem -Path $Path -Recurse
    foreach ($item in $items)
    {
        #Check if the item is a file or a folder
        if ($item.PSIsContainer) { $type = "Folder" }
        else { $type = "File" }
        
        #Report item has been found if verbose mode is selected
        if ($Verbose) { Write-Host Found a $type called $item.FullName }
        
        #Check if item name is 128 characters or more in length
        if ($item.Name.Length -gt 127)
        {
            Write-Host $type $item.Name is 128 characters or over and will need to be truncated -ForegroundColor Red
        }
        else
        {
            #Got this from http://powershell.com/cs/blogs/tips/archive/2011/05/20/finding-multiple-regex-matches.aspx
            $illegalChars = '[&{}~#%]'
            filter Matches($illegalChars)
            {
                $item.Name | Select-String -AllMatches $illegalChars |
                Select-Object -ExpandProperty Matches
                Select-Object -ExpandProperty Values
            }
            
            #Replace illegal characters with legal characters where found
            $newFileName = $item.Name
            Matches $illegalChars | ForEach-Object {
                Write-Host $type $item.FullName has the illegal character $_.Value -ForegroundColor Red
                #These characters may be used on the file system but not SharePoint
                if ($_.Value -match "&") { $newFileName = ($newFileName -replace "&", "and") }
                if ($_.Value -match "{") { $newFileName = ($newFileName -replace "{", "(") }
                if ($_.Value -match "}") { $newFileName = ($newFileName -replace "}", ")") }
                if ($_.Value -match "~") { $newFileName = ($newFileName -replace "~", "-") }
                if ($_.Value -match "#") { $newFileName = ($newFileName -replace "#", "") }
                if ($_.Value -match "%") { $newFileName = ($newFileName -replace "%", "") }
            }
            
            #Check for start, end and double periods
            if ($newFileName.StartsWith(".")) { Write-Host $type $item.FullName starts with a period -ForegroundColor red }
            while ($newFileName.StartsWith(".")) { $newFileName = $newFileName.TrimStart(".") }
            if ($newFileName.EndsWith(".")) { Write-Host $type $item.FullName ends with a period -ForegroundColor Red }
            while ($newFileName.EndsWith("."))   { $newFileName = $newFileName.TrimEnd(".") }
            if ($newFileName.Contains("..")) { Write-Host $type $item.FullName contains double periods -ForegroundColor red }
            while ($newFileName.Contains(".."))  { $newFileName = $newFileName.Replace("..", ".") }
            
            #Fix file and folder names if found and the Fix switch is specified
            if (($newFileName -ne $item.Name) -and ($Fix))
            {
                Rename-Item $item.FullName -NewName ($newFileName)
                Write-Host $type $item.Name has been changed to $newFileName -ForegroundColor Blue

            }
        }
    }
}

Once loaded, you can call the script using the following commands as examples:

Check-IllegalCharacters -Path C:\Files

The command above will check the folder path specified but will only report file and folder names detected with illegal characters or length.

Check-IllegalCharacters -Path C:\Files -Verbose

This command will also only report files and folder names detected with illegal characters or length, but this time it will also tell you names of the files and folders it has checked in the process. This can be used to make sure the script is checking all the locations you are expecting it to.

Check-IllegalCharacters -Path C:\Files -Fix

The command here will not only check file and folder names for illegal characters, but will also fix them using the rules specified in the script. You can customise these rules as you see fit, but I have gone with the following criteria:

Do not change files and folders with names of 128 characters or over (i.e., manually truncate them)
Replace two or more consecutive periods in a file or folder name with a single period

If the file or folder name either starts or finishes with a period, remove it
File or folder names containing illegal characters are processed as follows:

Replace ‘&’ with ‘and’
Replace ‘{‘ with ‘(‘
Replace ‘}’ with ‘)’
Replace “~” with “-“
Remove the ‘#’ character
Remove the ‘%’ character

An example running the script on some files and folders containing deliberately illegal characters is shown below:


The following screenshot shows the output from running the script:


And evidence that the files were renamed successfully…


Start all enabled timer jobs on a SharePoint 2010 farm using PowerShell and check their status

Get-SPTimerJob | where { $_.IsDisabled -eq $false } | sort $_.Name | ForEach-Object {
    try
    {  
        $timerJobName = $_.Name
        if ($_.WebApplication -ne $null) { $waMessage = "on web application $($_.WebApplication.Url)" }
        else { $waMessage = "on Farm" }
        Start-SPTimerJob -Identity $_
        Write-Host "Started timer job $timerJobName $waMessage"
    }
    catch
    {
        Write-Host "There was a problem starting timer job $timerjobName:" $_
    }
}


if you want to have report of current status of each timer job in the output file, then run the script


function Get-SPTimerJobStatus
{
    Get-SPTimerJob | sort Name | ForEach-Object

{
        $lastRun = $_.HistoryEntries | Select-Object -first 1
        if ($_.WebApplication -eq $null) { $level = "Farm" }
        else { $level = $_.WebApplication.Url }
       
        $values = @{
            "Name" = $_.Name
            "Level" = $level
            "StartTime" = $lastRun.StartTime
            "EndTime" = $lastRun.EndTime
            "Status" = $lastRun.Status
        }

        New-Object PSObject -Property $values | Select @("Name","Level","StartTime","EndTime","Status")

    }

}

Get-SPTimerJobStatus | Out-GridView










Perform an IISRESET on multiple servers using PowerShell

#Specify servers in an array variable

[array]$servers = "Server1","Server2","Server3","Server4"

#Step through each server in the array and perform an IISRESET
#Also show IIS service status after the reset has completed

foreach ($server in $servers)
{
    Write-Host "Restarting IIS on server $server..."
    IISRESET $server /noforce
    Write-Host "IIS status for server $server"
    IISRESET $server /status
}
Write-Host IIS has been restarted on all servers

Tuesday, January 12, 2016

Site Settings Part-8 ( Site Columns )

Before developing the lists, SharePoint content types and site columns we need to understand what is SharePoint list, content types etc. And why do we have to create them in the SharePoint site.
Lists are data containers in  SharePoint, where you can store the data of different data types. In SharePoint this content will get stored in the database and the content is very important for any organization.
So whenever you start developing any project the important question you need to ask the client is what type of data or different data types  you're maintaining or want to maintain in future. That data may be Sales documents, Finance documents, Project proposals and implementation documents, maintenance documents etc. These are all different kinds of data. In normal scenario document is a just a document, but in SharePoint you can have types of documents. Each type of document has its own metadata. The way you organize the data and persisting it and entire editing experience is a great thing in SharePoint.To manage the content we will create content Types.
I hope you got a little bit of understanding about the importance of SharePoint list and content type in SharePoint.
Site Columns:
Whenever you develop the SharePoint list and Content type, first develop required site columns that will be used while developing SharePoint lists and Content types.

what are site columns?

A site column is a reusable column definition, or template, that you can assign to multiple lists across multiple SharePoint sites. We will see how we achieve this.
How to create a SharePoint site column?

First of all, you will need to find the site settings in your SharePoint site You'll find this option in the right corner of your screen where the little setting icon is. If you click on it, you'll have a drop-down menu where you'll find the site settings. 



Once you get in there, you’ll see A LOT of different choices that we will probably understand someday, but for now, we will concentrate on the only choice that concerns us which is “site column”. If you really have time to kill, you can hover each choice and a little description will appear.

Once you click on the Site columns option, you’ll realize that there’s a list of a lot of existing ones already on your page. When I saw this, my question was: where did this all come from? It actually makes a lot of sense once you know it. Here’s what my page looks like when I click on this option:


As you can see, there are a lot of site columns already there. The reason is that when you create a Team Site in SharePoint like the one I have, SharePoint provides out-of-the-box apps (lists and libraries) that you can use. Of course, all of this doesn’t come from a magical place. The columns that appears in an app are site columns already available in your Team Site. Now, go back to the picture above, you’ll see that there’s a group called Core Contact and Calendar Columns. Obviously, you’ll find there the site columns that will appear if you create a Calendar in your site or a Contact list. I have to admit that I don’t understand all of the groups available and that’s normal since there’s still a lot to learn about the platform that I haven’t seen yet.
WARNING! Don’t ever delete one of the existing site columns. I’m not going to explain in details why you shouldn’t, but I’m sure you understand the impact of deleting a site column that is already used in SharePoint. It’s related to many different things in your site, so if one day it does not exist anymore, it’s going to cause problems when you will create a new app that requires this site column and much more. Honestly, I don’t know why you would delete one of them, but you never know. Actually, you should just never delete things inside your SharePoint that were already there when you created a new site. The fact is that it’s probably there for a reason and you never know when you’ll have to use that reason.
Let’s create a new site column. If you haven’t seen it in the page yet, there’s a little option on top of the list of existing site columns to create a new one.
SharePoint Site column types
The box that appears when you create a column in a list or a site column is quite similar, but there are a few new choices. 
Publishing Sites – Little Briefing
You have new column types that are especially there for Publishing site. A Publishing site lets you create new web pages in your site. For example, you could have a page layout to create articles and each time you add a new article, it creates a new page in your site with the article. Here’s the difference between the regular column types in a list and the columns types in a publishing page:
Publishing page
List
In a publishing page, your columns are the date you see, the content and the image which are all column types for publishing. The content type for publishing lets you display the content on the publishing page like in the example above of an article. The template on which your columns are displayed can vary according to your choices and you can put different column types for display like hyperlinks and summary links. On the other hand, in a list, the columns are always displayed the same way. You can’t display your columns in a template you chose like you would in a publishing page. I hope this gives you a good overview of the difference between column types for publishing and other column types. I haven’t seen all the possibilities associated to a publishing site, but I’m sure you get idea. If not, don’t worry about it, we will get to that subject in more details later in the series.
Once again, it is important to choose the right column type like I said in my other column types article because many types have impacts on other actions you can do in SharePoint.
SharePoint Site column group
Under your site column types, you have a field where you can choose in which group you want it to be. The groups are the segments you see in your site column list I’ve shown you before.
Most of the time you’ll probably choose custom columns which are like the “other” section. However, if you want to insert your new site column in an existing group you only have to click on the drop-down menu and they will all be there. You can also create a new group. For example, if you know you will have to create many site columns for any list or library that are related to invoices, you can create the group “Invoice” and you’ll be able to find them easily when the moment comes to create a new content type or when you need a specific column related to that.
How to use your SharePoint Site Columns in your lists or libraries?
Now, we’ve created our first site column! Then what? How do we insert a site column in an existing or new list/library? When I learned about site columns, we skipped that part and at one moment I realized I didn’t know at all what to do with those columns afterwards! It’s not the same process as for a column that you create directly in a list of course, but it’s not that difficult. A nice SharePoint developer explained it to me very quickly and I didn’t need more explanation.
Here it goes:
When you are in your list or library (we will use a list for this example) and you want to use one of your site columns, you have to go in your list settings. Once again, you can read my article on SharePoint 2013 navigation and UI if you don’t know where to find the list settings.
This is where you see all the settings you can change for your list including “Add from existing site columns” that you’ll find at the bottom of your page.
When you click on this option you’ll be able to choose the site column you want to add in your list.
Here’s where you’ll see the importance of adding your new site column in the right group when you create it. When your SharePoint site gets a lot bigger after some time, you’ll probably have a lot of available site columns. You’ll be happy to use the site column group filter to find the site column you need quickly instead of searching in the list of all the available site columns.
As you can see in the picture, you can add as much site columns as you want to your list. Therefore, if we create a new list of invoices, we might want to add many site columns created in the group “Invoice” that I mentioned before in my example.
Now, you probably understand why it is great to create site columns instead of creating a column directly in your list. You can then select all the columns you need in the new list or library you are creating, click ok and that’s it! You have a functional list or library very quickly.



Site Settings Part-7 ( Site Collection Administration )


Welcome to the last part of site settings in SharePoint 2013. So, let’s begin quickly.
Today, we will be discussing about Site Collection Administration features. Here, you can see the followingsettings in the below category. Let’s discuss about them one by one.

 Recycle Bin
Here, we have Recycle Bin with a new added feature showing the view as per the End User Recycle Bin items and Deleted from end user Recycle Bin.
Site Collection Features
The following are the Site Collection features. It contains default features and custom features (created by developers).



Site Hierarchy
The following view contains the Site Hierarchy which displays Content’s URLs, Titles of contents like (List & Document Library) and a link to Manage them directly going to content library and list settings.

Site Collection Navigation
This contains the site collection navigations which contain options to enable Navigation Enabled like the Left Navigation and Global Navigation, then we have Security Trimming and Audience Targeting to be enabled to all the sites in the Site Collection.

Search Engine Optimization Settings
Here in search engine optimization settings, we can optimize it by adding metatags in the pages. You also have an option to filter the link parameters to avoid link based on popularity coming up as the search option.


Site Collection Audit Settings
It is a beautiful feature to track down the log files for changes in the site contents like Editing items, Checking out or checking in Items or Moving or Copying items to another location in the site and lastly Deleting or restoring items.
It also logs in the events of searching feature, editing the content type or a column and even the changes in the permission levels.

Audit Log Reports
This feature is the same as the previous versions where the reports are generated on content viewing, content modifications, deletion, content type and list modifications all related to content activity reports, then we have Information Management Policy Reports which contains Policy modifications and Expiration and Disposition. Then under Security and Settings Reports, we have Auditing settings, Security Settings and Lastly under Custom Reports, we have Run a custom report in which you can configure your filter yourself to generate a report.
Portal Site Connection
Then, we have a new feature to connect to your own external content by entering the URL or the name to connect to the portal.

Content Type Policy Templates
Again a new feature in SharePoint 2013 where we can set up policy in content type as well which is to be satisfied before deleting it.
So as per below screen shot, you can either create one or Import a policy.

You can create the policy using the form below. You can add up Name and Administrative Description, then we have Policy Statement. You can have the Retention policy where you can schedule the content by specifying the sequence at each stage.
Then, we have Auditing specifying if you want to audit the items and documents subjected to policy. Lastly, Barcodes which can be included as per policy to the documents and Bar codes can be attached.


Then, as mentioned, we can Import the same settings to their other sites by exporting the similar kind of policy and importing it back.

Storage Metrics
Here, as we can see, it contains the size of the site on the right corner and all the contents below.


Site Collection App Permissions
It contains the App Names or the site content’s Display Name and their interface identifier regarding their permission level.
Site Policies
Here, you can create new Site Policy putting in Name, Description. Then, we have rules to have Site Closure and Deletion configuration where we have three options:
·         Do not close or delete site automatically
·         Delete sites automatically
·         Close and delete sites automatically
Lastly, we have Site Collection Closure settings which makes them as read only when it is closed.

Content Type Publishing
Then, we have content type publishing hubs where we can see we have Refresh All Published Content Types where we have an option to refresh all the updated content types in site collection level.

Then, we have Content type error log which contains errors that will cause during content type syndication for this site which will have the following fields - the Item, Failure Stage, Message and the time.


Lastly, we have the Hubs for storing the content types for our case, it is our site collection which will be storing the content types.
Site Collection Output Cache
As per our screen, we can see Site’s Output Cache settings. Where we have Output Cache option to enable or disable them, so it will enable it to generate the output using the query input by the Administrator.
Then, we can maintain a default page output Cache Profile where you can provide an option as to how long items should be held in cache.
Then, we can see a Page Output Cache Policy which will define the page which is to be used to provide the cache output values.
Lastly, we have an option for default Cached Debug information on the pages which will help us developers to closely track the error logs.

Popularity and Search Reports
Popularity and Search Reports are a part of generating Excel reports based on a lot of queries as shown in the screen shot.
They are as follows:
Usage Reports
Usage
This report shows historical usage information about the site collection, such as the number of views and unique users. Use this report to identify usage trends and to determine times of high and low activity.
This report shows popular search queries that received low click-through. Use this report to identify search queries that might create user dissatisfaction and to improve the discoverability of content. Then, consider using query rules to improve the query's results.
No Result Queries by Month
This report shows popular search queries that returned no results. Use this report to identify search queries that might create user dissatisfaction and to improve the discoverability of content. Then, consider using query rules to improve the query's results.
Usage Reports
Usage
This report shows historical usage information about the site collection, such as the number of views and unique users. Use this report to identify usage trends and to determine times of high and low activity.
Number of Queries
This report shows the number of search queries performed. Use this report to identify search query volume trends and to determine times of high and low search activity.
Search Reports
Top Queries by Day
This report shows the most popular search queries. Use this report to understand what types of information visitors are seeking.
Top Queries by Month
This report shows the most popular search queries. Use this report to understand what types of information visitors are seeking.
Abandoned Queries by Day
This report shows popular search queries that received low click-through. Use this report to identify search queries that might create user dissatisfaction and to improve the discoverability of content. Then, consider using query rules to improve the query's results.
Abandoned Queries by Month
This report shows popular search queries that received low click-through. Use this report to identify search queries that might create user dissatisfaction and to improve the discoverability of content. Then, consider using query rules to improve the query's results.
No Result Queries by Day
This report shows popular search queries that returned no results. Use this report to identify search queries that might create user dissatisfaction and to improve the discoverability of content. Then, consider using query rules to improve the query's results.
No Result Queries by Month
This report shows popular search queries that returned no results. Use this report to identify search queries that might create user dissatisfaction and to improve the discoverability of content. Then, consider using query rules to improve the query's results.
Query Rule Usage by Day
This report shows how often query rules fire, how many dictionary terms they use, and how often users click their promoted results. Use this report to see how useful your query rules and promoted results are to users.
Query Rule Usage by Month
This report shows how often query rules fire, how many dictionary terms they use, and how often users click their promoted results. Use this report to see how useful your query rules and promoted results are to users.


Variations Settings
Then, we have the Variation settings which is a very important feature. It is like how the labels will perform when you create a new site, list or a page.
You can also recreate the deleted pages and also you can have a check on the updates on a web part while you are updating one of them.
Lastly sending notifications on newly created or updated items.

Variations Labels
In this part of settings, we can create a new label as per the form below:
Firstly, we can set up the language, then the type of what the label will be, then we will have the Variation Homesite URL, Label name and Description, the Display Name and lastly contracts to put in users who can actually receive notifications.

Translatable Columns
Here, you can select the columns you would like all lists on your targets to translate by default. Individual lists may choose to customize their settings through the Library Settings on the Library tab.
Suggested Content Browser Locations
Here we can have suggested content browser locations settings.
We can have the Display name, url, Description for the content browser locations to be suggested.
HTML Field Security
Here, we can insert external iframes in HTML fields on pages in the site where you can set permissions on the pages to show dynamic content from other web sites and also it will add iframes from this domain.

SharePoint Designer Settings
Here, we see SharePoint Designer Settings for the first time where a developer can configure SharePointDesigner to be enabled or disabled on the site, then we have Enable Detaching Pages from the Site Definition where it states whether to allow Site Owners and Designers to detach pages from the original site. Then, we can see Enable Customizing Master Pages and Page Layouts, where Owners and Designers can be assigned access to Master Pages and other Page Layouts and lastly Enable Managing of the Web Site URL Structure to provide them with access to allow structure of their web site using Designer.

Site Collection Health Checks

This is nothing but a Microsoft Console which will run and check the Site’s space size, load on the site and other statistics parameters.

Site Collection Upgrade
Here, this is a new feature where the site is upgraded, according to the changes made on the master pages and page layouts.
We can see in the below screen shots to see our upgrades.



References : Microsoft & CodeProject