Showing posts with label Krsto Savic. Show all posts
Showing posts with label Krsto Savic. Show all posts

Monday, June 27, 2016

User Profile Synchronization Service issue

Last week I experienced major problem which took me more than two days to resolve. On one of our SharePoint farms User Profile Synchronization Service was stopped, and nothing I tried could not help to start it. And believe me, I tried almost everything I read on internet. But no, service was stubborn, not wanting to start. Then after two days of wall hitting I noticed following entry in ULS log file:

Failed to set the new Service Broker on database User_SyncDatabase on server SQL. Exception: The operation cannot be performed on database "User_SyncDatabase" because it is involved in a database mirroring session or an availability group. Some operations are not allowed on a database that is participating in a database mirroring session or in an availability group.  ALTER DATABASE statement failed.  ALTER DATABASE statement failed.

It turned out that the reason for all this mess is because all SharePoint database are in SQL High Availability group, despite the fact that Microsoft is claiming that this is allowed (http://ift.tt/291xETQ).

Just by removing User_SyncDatabase from High Availabilty group User Profile Synchronization service was started without a glitch. Go figure!

After starting the service, I returned database to HA group, and everything is working without further issues.

Of course, documentation regarding this strange behavior does not exist, there is only one blog explaining this, and it is on Russian. For those who can understand it, here it is: http://ift.tt/28XXRQw

I hope my blog post will help some poor soul, who lost all hopes that User Profile Synchronization Service would start ever again. For sure, I needed one.

 


by Krsto Savic via Everyone's Blog Posts - SharePoint Community

Thursday, May 12, 2016

Get content and security permissions for one SharePoint library

This will be a short blog. Did you ever have to list all files and security rights for one of the libraries? If no, you never had to deal with people from audit or security department, you lucky bastards :-)

Anyway, if you have one or several important document libraries, especially with bunch of folders, sub-folders, each one with different security permissions, preparing report for security guys can be real pain in the neck if you have to check everything manually. Lucky for us there is PowerShell to make our life easier.

I found several scripts which gets you permissions for all sites and all the libraries, and they are not bad, but it takes them forever to finish. Also they will provide you with a pile of unnecessary data, which you need to put in order later. Likewise, almost all of them collect up to library permissions and do not check folder permissions inside the libraries.

That is the reason I have created small script which will list you all the content and permissions for just one library. Result display is not among most pretty, but it serves the purpose.

Get-SPListFolderPermissions.ps1

Script will provide you folder url, folder security rights as well as names of all items inside it. Also files located in library root will be displayed with their security permissions.


by Krsto Savic via Everyone's Blog Posts - SharePoint Community

Wednesday, April 27, 2016

Archiving Absence of Leave calendar in SharePoint 2013

In our Company we have Absence of Leave calendar, where all employees add their vacations, sick days, holidays etc. Over the years this calendar grow quite a bit, with over 10.000 entries. As you are aware, Microsoft recommendation for entry numbers is no more than 5.000. Recently we have experienced some strange behavior in this list, some entries were duplicated, views did not work as it should. All in all, it was time to archive this list and start with fresh one. 

First thing is to create new calendar. Because Absence calendar has various columns and views, the easiest way was to save current Absence calendar as template, and then to create Absence-new calendar from that template. So, first go to Absence calendar, open Calendar tab and choose List Settings:

Under Permissions and Management click Save list as template option:

Choose a File Name, Template Name and Template description, in my case I called it Absence-template. Leave Include Content box unchecked, we want to save empty list, and then click OK

Once we have created template, we can use it to create new calendar. Go to Site Contents, choose Add an App, in search field type absence, in order to find Absence-template, choose Absence-template and in Name field type Absence-new. Upon clicking on Create button new Calendar will be created.

Now we have old calendar named Absence and new calendar called Absence-new. Next step is to rename them, so Absence will become Absence-archive, and Absence-new will become Absence. Go to Absence calendar, open Calendar, choose List Settings, and under General Settings click List name, description and navigation:

Change calendar name to Absence-archive and in Navigation section remove this list from Quick launch:

Do the same steps to Absence-new calendar, change its name to Absence and display this calendar to Quick launch.

This is as far as we can go with GUI, from now on we are going to need PowerShell.

Let us summarize what we did so far; we have created template from old calendar allowing us to use this template in order to create new calendar with same columns and views. After that we renamed old calendar to Absence-archive and remove it from Quick launch, also we renamed new calendar to Absence and added it to Quick launch. You may think that this is all we must do, but you would be wrong. We did change calendar names but URLs to list remained the same. URL to list Absence-archive is:

http://ift.tt/1SzZUYO

and for Absence:

http://ift.tt/1VBC0BV

so we must change root folders for these calendars. Why to do this, you may wonder. I can think of three reasons; first one would be that some services and scripts are using data from this calendar, so if don't change root folder they will not collect data from active calendar. Second reason is that some users have bookmarked this calendar, and will keep on looking in old calendar. This could lead to some misunderstandings and communication problems. And third one is that there will always be someone asking why there is difference between calendar names and URLs, and if this question escalate, you will end up changing URLs. So why not do it right now?

Calendar URL can be changed on few different ways, but easiest way is through PowerShell. Open PowerShell management console and run this script:

Add-PSSnapin Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

$libOriginalUrl = "/Lists/Absence";
$libNewUrl = "/Lists/Absence-archive";
$web = Get-SPWeb -Identity http://ift.tt/1VBC0BX

$lib = $web.GetList($web.Url + $libOriginalUrl)
$rootFolder = $lib.RootFolder;
$rootFolder.MoveTo($web.Url + $libNewUrl)

Run this script both for Absence and Absence-archive calendar, by changing $libOriginalUrl and $libNewUrl.

Once we changed URLs all is left to do is to add data to new Absence calendar. Because this is Absence calendar, there are events which are recurring, like religious holidays, or domestic holidays. Also there is need to add events which are still in progress, or better yet, which end date is still in the future. We can not ask employees to insert events again just because we archived calendar. 

To add active events to new calendar we need PowerShell script. This script get all events which end date is greater that now, and copy event fields to new calendar:

Add-PSSnapin Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

$web = Get-SPWeb -Identity http://ift.tt/1VBC0BX
$sourcelibrary = $web.Lists["Absence-archive"]
$destlibrary = $web.Lists["Absence"]
$sourcefields = $sourcelibrary.Fields

$sourceitems = $sourcelibrary.GetItems() | Where-Object {$_["EndDate"] -gt (Get-Date)}
foreach ($item in $sourceitems) {
    $newdestitem = $destlibrary.AddItem()
    foreach ($field in $sourcefields) {
        if (($field.ReadOnlyField -ne $True) -and ($field.InternalName -ne "Attachments")) {
            $newdestitem[$($field.InternalName)] = $item[$($field.InternalName)]
            }       
        }
        $newdestitem.Update()
    }

Upon successfully updating of events, your new calendar is up and running. With PowerShell scripts whole process of archiving calendar can last just few minutes, depending of number of events we need to copy.


by Krsto Savic via Everyone's Blog Posts - SharePoint Community

Friday, February 26, 2016

PowerShell PSRemoting error on SharePoint servers

Last week I run into very strange issue, which took me days to figure out and resolve it. It is not directly involved with SharePoint, but it can give you a lot of headache.

As a part of much greater project, one of my tasks was to enable PSRemoting on SharePoint server. The problem was that our clients have SharePoint 2010 on Windows 2008R2 servers, on which PSRemoting is not enabled automatically. So we had to enable PSRemoting on all of these servers. In order to save time, we implemented group policy to enable PSRemoting on all servers. Once implemented, I tried to connect to one of SharePoint 2010 servers, let's call it SPTest, and received following message:

Enter-PSSession -ComputerName SPTest

Enter-PSSession : Connecting to remote server SPTest failed with the following error message : WinRM cannot process the request. The following error with errorcode 0x80090311 occurred while using Kerberos authentication: There are currently no logon servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTTPS transport. Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic. At line:1 char:1 + Enter-PSSession -ComputerName SPTest

My first thought was that something went wrong with configuring WinRM service on server, because I was able to connect to other, non-SharePoint servers. After manually enabling PSRemoting nothing changed, same error message appeared. I searched Event log on SharePoint server and there was nothing which would indicate what went wrong. Also when I tried Test-WSMan cmdlet it stated that everything is properly configured. Very strange.

After looking in Event Viewer on my client machine, I found following error message:

The Kerberos client received a KRB_AP_ERR_MODIFIED error from the server SPTest$. The target name used was HTTP/SPTest. This indicates that the target server failed to decrypt the ticket provided by the client. This can occur when the target server principal name (SPN) is registered on an account other than the account the target service is using. Ensure that the target SPN is only registered on the account used by the server. This error can also happen if the target service account password is different than what is configured on the Kerberos Key Distribution Center for that target service. Ensure that the service on the server and the KDC are both configured to use the same password. If the server name is not fully qualified, and the target domain (ADTest.COM) is different from the client domain (ADTest.COM), check if there are identically named server accounts in these two domains, or use the fully-qualified name to identify the server.

Ok, this problem has something to do with Kerberos. But what? SPTest machine is joined into domain, and everything is configured properly. How can the ticket be the problem? After consulting Google found this blog: http://ift.tt/1LOq8mf by Damien Caro, where he explained  that, if you have Application pools running under a domain service account, you may run into same issue, since WinRM seems to check for a HTTP SPN set on the computer object (HTTP\name-of-the-server), it will always fail because it will find the HTTP SPN but not set on the computer object. Thus, it cannot authenticate using Kerberos and just fails. It turned out that this is what was causing the problem from the beginning.

I found two solutions for this issue.

First one is quick and dirty, you just have to add one more DNS A record for you machine, or add record to your host file, adding different name for your server with same IP address. For instance, my server name is SPTest, I added in my client machine host file SPTest_PSRemoting with same IP address. After that I tried Enter-PSSession -ComputerName SPTest_PSRemoting and it worked! However, this solution is applicable just for testing purposes, you don't want to add additional DNS record for all of your servers, or hassle with host files.

The other solution is to configure your Service account to utilize SPN  just for ports used by Web applications. This includes typing few commands in command prompt, but be careful, you first need to make a list of all the ports your IIS server is using for Web applications.

First step was to query SPN, I opened command prompt and typed:   

C:\Windows\system32>setspn -Q http/SPTest
Checking domain DC=ADTest,DC=com
CN=SPS_WebApp,OU=Users,DC=ADTest,DC=com
HTTP/SPTEST.ADTest.com
HTTP/SPTEST
HTTP/report
HTTP/reportstaging
HTTP/reporttest
HTTP/reportdev

Existing SPN found!

You can see that Service account SPS_WebApp has SPN HTTP/SPTEST, and since WinRM seems to check for a HTTP SPN set on the computer object (HTTP\SPTEST), it will always fail because it will find the HTTP SPN but not set on the computer object, but on Service account. Thus, it cannot authenticate using Kerberos and just fails.

To get the WinRM Windows Service remote connection to work, narrow the scope of the SPN to the port number for the website. Rather than adding:

HTTP/SPTest.ADTest.com
use
HTTP/SPTest.ADTest.com:80

In this case the services are hosted in the web site running on port 80. The WinRM service runs on port 5195 by default and therefore does not match on the port specific SPN. Rather than specifying port, it is also possible to use the NETBIOS name for the network host if the fully qualified domain name is used for the SPN.

For instance IIS server on my machine uses 3 ports (80,81 and 85) for different Web Applications.

First I had to add SPN which included the ports:

Setspn -S http/SPTest:80 ADTest\SPS_WebApp
Setspn -S http/SPTest.ADtest,com:80 ADTest\SPS_WebApp
Setspn -S http/SPTest:81 ADTest\SPS_WebApp
Setspn -S http/SPTest.ADtest,com:81 ADTest\SPS_WebApp
Setspn -S http/SPTest:85 ADTest\SPS_WebApp
Setspn -S http/SPTest.ADtest,com:85 ADTest\SPS_WebApp

After that, had to delete SPN:

Setspn -D http/SPTest ADTest\SPS_WebApp
Setspn -D http/SPTest.ADtest,com ADTest\SPS_WebApp

And that's it! Once I checked SPN for http/SPtest and received message that no such SPN was found:

C:\Windows\system32>setspn -Q http/SPTest
Checking domain DC=ADTest,DC=com
No such SPN found.

But after querying SPN with explicit port got the following:

C:\Windows\system32>setspn -Q http/SPTest:80
Checking domain DC=ADTest,DC=com
CN=SPS_WebApp,OU=Users,DC=ADTest,DC=com
HTTP/SPTEST.ADTest.com:80
HTTP/SPTEST:80
HTTP/SPTEST.ADTest.com:81
HTTP/SPTEST:81
HTTP/SPTEST.ADTest.com:85
HTTP/SPTEST:85
HTTP/report
HTTP/reportstaging
HTTP/reporttest
HTTP/reportdev

After this intervention I had no more problems with connecting to SharePoint servers.


by Krsto Savic via Everyone's Blog Posts - SharePoint Community

Wednesday, February 10, 2016

Add Comic book web part

On our internal SharePoint server we have IT sub site and on default page we have Image Viewer Web part which shows Dilbert comic images. From time to time we change comic image, and we used to do it by hand, changing image URL manually.

I got tired of changing images manually, so I created small script which will do hard work instead of me. You may ask: "Why do this when you have already created web parts, which will do exactly the same thing?" Well, for one thing, some companies prohibit installation of web parts from unknown sources. Also, this script can be recycled and used for some other purposes. For instance, you can add pictures with security tips and advises on your SharePoint default page, and then use this script to change it in regular intervals. And last, I wanted to see how difficult it is to create such a script :).

It turned out it is not that difficult. I will explain all necessary steps:

1. Create document library for images; You can create new document library to store images, or you can use existing one. On our site I used existing library called Images, just created folder Dilbert in it. There I put Dilbert comic images.

2. Edit site default page, add Image Viewer web part in it (Page > Edit Page > Add Web Part > Media and Content > Image Viewer).

3. Change a title of web part to Dilbert, you can also add some image for testing purposes, and change Alternative Text to Dilbert. Of course, if you want, you can customize this web part according to your desires.

4. Save Add-DilbertComic.ps1 script on some location on SharePoint server (for instance "C:\ScheduledTasks"). You need to change web site URL, library name and web part title according to your configuration. Here is an example how script should look like:

#This script randomly takes pictures from document library and place it in webpart on default site page
# Created by Krsto Savic

Add-PSSnapin Microsoft.SharePoint.Powershell
$web = get-spweb http://ift.tt/20opMKE
$list = $web.Lists | where {$_.title -eq "Images"}
$PicUrl = ($list.items | where {$_.file -like "Images/Dilbert/*"} | get-random).url
$page = $web.GetFile(“default.aspx”)
$page.CheckOut()
$wpm = $web.GetLimitedWebPartManager($page.Url, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$wp = $wpm.WebParts | Where-Object { $_.Title -eq “Dilbert” }
$wp.ImageLink = “/it/$PicUrl"
$wpm.SaveChanges($wp)
$page.CheckIn(“Changed Dilbert Webpart”,[Microsoft.SharePoint.SPCheckinType]::MajorCheckIn)
$web.Close()

After this, you need to test the script. Open SharePoint Management Shell and start the script to see if the pictures are changing in web part. Of course, I don't have to tell you that you need to run Management Shell as Shell administrator, and to open Shell using Run as Administrator. Right?

5. Once you tested script, all what is left is to configure Scheduled task to run this script on regular intervals:

  1. On the system that the task will be run from, open the Windows Task Scheduler. This can be found in the Start menu, under Start > Administrative Tools.

  2. In the Task Scheduler, select the Create Task option under the Actions heading on the right-hand side.

  3. Enter a name for the task (for instance Change Dilbert comic), and give it a description (the description is optional and not required).

  4. In the General tab, go to the Security options heading and specify the user account that the task should be run under. Change the settings so the task will run if the user is logged in or not. It is best to use account with Shell administrator rights, and with password never expires option configured. You can use SharePoint farm account, or some other SharePoint admin account. 

  5. Next, select the Triggers tab, and click New to add a new trigger for the scheduled task. This new task should use the On a schedule option. The start date can be set to a desired time, and the frequency and duration of the task can be set based on your specific needs. For instance, set it to run weekly, every Sunday at 11pm. In that way, every Monday users will have fresh copy of comic to read. Click OK when your desired settings are entered.

  6. Next, go to the Actions tab and click New to set the action for this task to run. Set the Action to Start a program.

  7. In the Program/script box enter "PowerShell."

    In the Add arguments (optional) box enter the value ".\[Your PowerShell Script Name]." For example, if your PowerShell Script is named "Add-DilbertComic.ps1" then you would enter ".\Add-DilbertComic.ps1" as the value.

    Then, in the Start in (optional) box, add the location of the folder that contains your PowerShell script. In this example, the script is in a folder called "ScheduledTasks" that is off the root C: drive.

    Note: The location used in the Start in box will also be used for storing the scheduled task run times, the job history for the copies, and any additional logging that may occur.

    Click OK when all the desired settings are made.

  8. Next, set any other desired settings in the Conditions and Settings tabs. You can also set up additional actions, such as emailing an Administrator each time the script is run.

  9. Once all the desired actions have been made (or added), click OK. The task will be immediately set, and is ready to run.

  10. Try ti run task manually to see if it is working.

And that's it. You have your own custom web part which change comic book picture every week.

Add-DilbertComic.ps1


by Krsto Savic via Everyone's Blog Posts - SharePoint Community

Monday, December 28, 2015

Creating SharePoint folders via PowerShell

I know that there are lot of sites and scripts where you can find how to create bunch of folders and set permissions on them via PowerShell. But I was not able to find all in one place. For instance, how to create folder, how to add AD user or group with certain permission level, how to set permission inheritance on some folder etc.

Therefore I wrote couple of functions which will hopefully help you to configure your folder structure, as well as necessary permissions. Best thing is that you can create .csv file and create load of folders and permissions at once.

SharePoint-CreateFolders.ps1

folderpermission.csv

<#
.Synopsis
   This function creates folder in SharePoint list
.DESCRIPTION
   This function creates folder in SharePoint list
.EXAMPLE
    Create-SPFolder -WebURL http://ift.tt/1MCEB4D -listName Listname -RootFolderURL Listname -FolderName MyFirstFolder -Verbose
#>
function Create-SPFolder
{
    [CmdletBinding()]

    Param
    (
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
                   $WebURL,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
                   $listName,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
                   $RootFolderURL,
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
                   $FolderName
    )

    Begin
        {
        $website = Get-SPWeb $WebURL
        $list = $website.Lists[$listname]
        
        }
    Process
        {
        If ($website.GetFolder("$RootFolderURL/$foldername").Exists){
            Write-Verbose "SharePoint folder already exists. Skiping...."
            }
        
        else{
            $folder = $list.AddItem($RootFolderURL, [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, "$folderName")
            $folder.Update()
            Write-Verbose "SharePoint folder $foldername created on location $RootFolderURL/$foldername"
            }
        }
    End
        {
        $web.Dispose()
        }
    }    



<#

.Synopsis
   This function sets permissions to SharePoint folder

.DESCRIPTION
   This function sets permissions to SharePoint folder; it breaks inheritance and add AD user with defined permission level

.EXAMPLE1

   Set-SPFolderUserUniquePermission -WebURL http://ift.tt/1MCEB4D -listName Listname -FolderURL "Listname/MyFirstFolderName" -PermissionLevel "Contribute" -User AD\MyAccount -Verbose

.EXAMPLE2

   Set-SPFolderUserUniquePermission http://ift.tt/1MCEB4D "Listname" "Listname/MyFirstFolderName" -PermissionLevel "Read" AD\MyAccount -Verbose

.EXAMPLE3
   
   $csv = Import-Csv C:\temp\folderpermission.csv

foreach ($line in $csv){
    
    Set-SPFolderUserUniquePermission -WebURL $line.weburl -listName $line.listName -FolderURL $line.FolderUrl -PermissionLevel $line.PermissionLevel -User $line.ADUser -Verbose
    
    }
#>
function Set-SPFolderUserUniquePermission
    {
    [CmdletBinding()]

    Param
    (
     
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
                   $WebURL,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
                   $listName,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
                   $FolderURL,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=3)]
                   $PermissionLevel,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=4)]
                   $User

    )

    Begin
        {
        $website = Get-SPWeb $WebURL
        $list = $website.Lists | Where-Object{$_.title -eq $listName}
        $SPfolder = $list.Folders | Where-Object {$_.url -eq $FolderURL}
        $group = $website.SiteUsers[$user];  
        }

    Process
        {
        $spFolder.BreakRoleInheritance($false);
        $roleAssignment = New-Object microsoft.sharepoint.SPRoleAssignment($group)
        $roleDefinition = $website.RoleDefinitions[$PermissionLevel]
        $roleAssignment.RoleDefinitionBindings.Add($roleDefinition)  
        $spFolder.RoleAssignments.Add($roleAssignment)       
        $spFolder.Update()   
        }
    End
        {
        $website.Dispose()
        }
    }


<#
.Synopsis
   This function set SharePoint folder permission to inherit from parent.

.DESCRIPTION
   This function set SharePoint folder permission to inherit from parent.

.EXAMPLE1

   Set-SPFolderInheritPermission -WebURL http://ift.tt/1MCEB4D -listName Listname -FolderURL "Listname/MyFirstFolderName"

.EXAMPLE2

   $csv = Import-Csv C:\temp\folderpermission.csv

foreach ($line in $csv){
    
    Set-SPFolderInheritPermission -WebURL $line.weburl -listName $line.listName -FolderURL $line.FolderUrl
    }
#>
function Set-SPFolderInheritPermission
{
    [CmdletBinding()]

    Param
    (
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
                   $WebURL,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
                   $listName,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
                   $FolderURL
    )

    Begin
        {
        $website = Get-SPWeb $WebURL
        $list = $website.Lists | Where-Object{$_.title -eq $listName}
        $SPfolder = $list.Folders | Where-Object {$_.url -eq $FolderURL}
        }
    Process
        {
        $spFolder.ResetRoleInheritance()
        $spFolder.Update()
        }
    End
        {
        $website.Dispose()
        }
    }


<#

.Synopsis
   This function sets permissions to SharePoint folder

.DESCRIPTION
   This function sets permissions to SharePoint folder; it breaks inheritance and add SharePoint group with defined permission level

.EXAMPLE1

   Set-SPFolderGroupUniquePermission -WebURL http://ift.tt/1MCEB4D -listName Listname -FolderURL "Listname/MyFirstFolderName" -PermissionLevel "Contribute" -SPGroup "HR" -Verbose

.EXAMPLE2

   Set-SPFolderGroupUniquePermission http://ift.tt/1MCEB4D "Listname" "Listname/MyFirstFolderName" -PermissionLevel "Read" "HR" -Verbose

.EXAMPLE3
   
   $csv = Import-Csv C:\temp\folderpermission.csv

foreach ($line in $csv){
    
    Set-SPFolderGroupUniquePermission -WebURL $line.weburl -listName $line.listName -FolderURL $line.FolderUrl -PermissionLevel $line.PermissionLevel -Group $line.SPGroup -Verbose
    
    }
#>
function Set-SPFolderGroupUniquePermission
    {
    [CmdletBinding()]

    Param
    (
     
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
                   $WebURL,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
                   $listName,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=2)]
                   $FolderURL,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=3)]
                   $PermissionLevel,

        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=4)]
                   $SPGroup

    )

    Begin
        {
        $website = Get-SPWeb $WebURL
        $list = $website.Lists | Where-Object{$_.title -eq $listName}
        $SPfolder = $list.Folders | Where-Object {$_.url -eq $FolderURL}
        $group = $website.SiteGroups[$SPGroup];  
        }

    Process
        {
        $spFolder.BreakRoleInheritance($false);
        $roleAssignment = New-Object microsoft.sharepoint.SPRoleAssignment($group)
        $roleDefinition = $website.RoleDefinitions[$PermissionLevel]
        $roleAssignment.RoleDefinitionBindings.Add($roleDefinition)  
        $spFolder.RoleAssignments.Add($roleAssignment)       
        $spFolder.Update()   
        }
    End
        {
        $website.Dispose()
        }
    }





$csv = Import-Csv C:\temp\folderpermission.csv

foreach ($line in $csv){

    Create-SPFolder -WebURL $line.WebUrl -listName $line.ListName -RootFolderURL $line.RootFolderUrl -FolderName $line.FolderName -Verbose
    }

foreach ($line in $csv){
    
    $FolderUrl = $line.RootFolderUrl + '/' + $line.FolderName
    Set-SPFolderInheritPermission -WebURL $line.WebUrl -listName $line.ListName -FolderURL $FolderUrl -Verbose
    }

foreach ($line in $csv){
    
    $FolderUrl = $line.RootFolderUrl + '/' + $line.FolderName
    if($line.SPGroup){
        Set-SPFolderGroupUniquePermission -WebURL $line.WebUrl -listName $line.ListName -FolderURL $FolderUrl -PermissionLevel $line.PermissionLevel -SPGroup $line.SPGroup -Verbose
        Write-host $line.ADUser $line.SPGroup $FolderUrl
        }
    elseif($line.ADUser){
        Set-SPFolderUserUniquePermission -WebURL $line.WebUrl -listName $line.ListName -FolderURL $FolderUrl -PermissionLevel $line.PermissionLevel -User $line.ADUser -Verbose
        Write-host $line.ADUser $line.SPGroup $FolderUrl
        }
    else{
        Write-Verbose "No security groups to configure. Skiping...."
        }
    }

   
 


by Krsto Savic via Everyone's Blog Posts - SharePoint Community

Monday, November 30, 2015

IIS Application Pool identity password

I recently run on something cool and scary at the same time. While creating a script for creating custom SharePoint web application, I needed to change IIS Application pool identity account.

It turns out it was easier than I imagine, you need just couple lines of code:

            import-module webadministration

            $AppPool = get-childitem IIS:\AppPools | where {$_.name -eq "Services"}

            $credential = Get-Credential
            $AppPool.processModel.userName = $credential.UserName
            $AppPool.processModel.password = $credential.GetNetworkCredential().password
            $AppPool.processModel.identityType = 3
            $AppPool | Set-Item
            $AppPool | Restart-WebAppPool

But what surprised me is that you can, with a simple command, extract Application Pool identity password. All you need is a simple one liner:

(get-childitem IIS:\AppPools | where{$_.name -eq "Services"}).processModel

In third row you can see a password property and its value in plain text! How freaking is that!

According to Microsoft this is a feature and also:

"For maximum security, application pools should run under a special built-in identity called ApplicationPoolIdentity. There are two types of Identity for the application pools: Built-in and Custom. The built-in accounts are ApplicationPoolIdentity, NetworkService, LocalService, and LocalSystem. The default (recommended) and most secure is ApplicationPoolIdentity."

This is all true, but there are many web applications (SharePoint, for instance) which requires custom application pool identity. And with a simple PowerShell command you can read its password.

So please be careful and never give Application pool identity account more rights as necessary. Imagine if you put SharePoint farm admin account to run Application pool. Or even worse, your domain admin account.


by Krsto Savic via Everyone's Blog Posts - SharePoint Community

Monday, October 12, 2015

Installing Cumulative Updates on SharePoint 2013

Patching SharePoint with Cumulative Updates - do it or don't do it . Always a dilemma.  Cumulative Updates includes security fixes as well as fixes for other reported problems. It is also important to mention that Cumulative Updates do not contain new functionalities; new SharePoint functionalities comes with Service Packs. 

New Microsoft policy is to release SharePoint Cumulative Updates once every month. For a security point of view it is highly recommended to install these updates, even more if your SharePoint farm is exposed to internet. But then again it is time consuming, risky job with downtime of your services.

Moreover, there is no rollback procedure recommended by Microsoft, for them rollback is to cross your fingers and hope for the best. If something happens look at logs and try to fix issues manually which will even more increase downtime of your services. Pretty scary stuff, right?

In theory it all looks like a piece of cake; install patches on server, start SharePoint Products Configuration Wizard, click Next couple of times and seat back and observe progress bar. But this is just a theory, reality is a bit different.

Things are getting a bit complicated when you have multiple servers in the farm. According to Microsoft recommended procedure is to install patches on application servers, then on web servers, and then to start upgrade in same order. For detail information please see http://ift.tt/1G28bUX. Also there is a great blog by Samuel Betts, where he explained in detail process of patching multiple farm servers (http://ift.tt/1avd07V).

That is not all; there is also a problem with patching duration. Installing patches can last for hours depending of how server is busy. Just imagine: You have two front end and two application servers to update and for each you have to spend three hours for installation! Even if you combine installations it will be over 5 hours just for installation! And that is only half of the job.

As I said before, rollback procedure, according to Microsoft, does not exist. You can not uninstall patches once they are installed. So if your installation package reports a failure and can not be installed all the way, you are stuck with updates which were installed before installation failure. You get half baked cookie! To make matters worse, you will not be able to do finish SharePoint Product Configuration because your SharePoint farm servers will not be at same patch level.

As you can see, there is a lot to take into consideration when implementing patches on SharePoint servers. However, thanks to fellow bloggers you can learn a trick or two and decrease the risks and installation time, and therefore application downtime.

In our company there is SharePoint farm with three front end servers and one application server, so when it comes time to apply SharePoint updates you need to be prepared and informed. Usually we update SharePoint server during weekends and with previous announcement to other colleagues that the service will be unavailable.

Step 1. Backup

Before you start to do anything it is a smart thing do to backup. First I do farm backup - this is my last resort if everything else fails. You can schedule farm backup to be done during the Friday night, so when you start a patching process on Saturday morning you don't have to wait for a farm backup to complete. Off course, there is a risk that someone was altering something during the night, but let's be honest, chances for that are minimal. Also, there is a great chance that you will never gonna do farm restore, but you never know. Better to be safe than sorry later.

Although farm backup is good start, you can not do rollback just from it.

There is very nice blog by Chris Mullendore about taking snapshots of SharePoint servers (http://ift.tt/ZokzVc) from which I realized that there is a safe way to take snapshots and not to worry much about consistency. 

So what I do is to turn off all SharePoint servers (key is to turn off all of them), take snapshots of all servers, and also do backup of all SharePoint databases. Of course, you can backup databases earlier, but I prefer this way, because in this way all crucial components are backed up in the same point in time. Chris in his blog have mentioned potential risk of a loss of connectivity to Active Directory due to a machines have changed their account passwords, but that is a small risk. If you want to be sure just check PasswordLastSet property on your SharePoint servers using this command:

(get-adcomputer <servername> -Properties passwordlastset).passwordlastset

In most cases machine password duration is 30 days, so if your password is set later you are in the clear.

Shutting down SharePoint servers off course means downtime of services. Depending on amount of data on servers and databases, snapshot of servers and backup of databases can take a while. In our case it takes about a hour - hour and a half to complete this task. But this is small price to pay.

This is a good time to point out that creating a backup and rollback plan is very important part of patching procedure. It is better to loose hour or two for creating backups then to loose your job because you have no rollback plan when something goes wrong. Excuses like 'What can go wrong?' or 'I have done this 100 of times and never had problem.' are never in place. We are professionals and it is our job to do everything in our power to complete task as efficient and painless as possible.

Step 2. Update installation

So far we created farm backup (just in case), snapshots of all SharePoint servers and backup of SharePoint databases. Next step is to install patches on servers.

Russ Maxwell wrote great blog how to reduce amount of time needed for patch installation on SharePoint servers (see http://ift.tt/Z1qnIV). Better yet, he wrote a code which automates installation process; it shuts down all necessary services, installs update and starts services again. Code also pauses search service application. This code dramatically decreases patching time. All you need to do is to save Patchit.ps1 file in the same folder with patch installation and run it. Of course you need to start SharePoint 2013 Management Shell with administrative rights and start script from there, but you already knew that, right?

Patchit.ps1

I copy installation files along with Patchit.ps1 script to all SharePoint servers, and then start patching. First I  install updates on application server, and then on web servers. After that I usually check event log to see if there is some errors and if all updates were installed successfully. Only when I verify that everything is installed as it should be I can proceed to next step. If something goes wrong and cannot be fixed rollback procedure can be activated (rollback procedure will be explained later).

Step 3. SharePoint upgrade

Let us recapitulate what we have done so far. We have create backups and took snapshots of our SharePoint servers. After that, using Patchit.ps1 script, we have installed Cumulative Update on servers, first on application server and then on web front end servers.

Next step is to run SharePoint upgrade. This can be done in two ways, one way is to start SharePoint 2013 Products Configuration Wizard, which is located in Microsoft SharePoint 2013 Product folder. Other way is to run PSConfig script, which is my preferred way, and I use it whenever I can.

According to TechNet article http://ift.tt/1G28bUZ, proper upgrade order is to upgrade specific services first, upgrade content databases next, and then proceed with server upgrade. In our environment we don't have specific services so I go to upgrading content databases. This is an optional step, but it will help ensure that all content databases are upgraded first. It has the advantage of enabling some parallelism to reduce the outage time. If it is not performed, all remaining non-upgraded content databases will be upgraded serially when you run the SharePoint upgrade to upgrade the farm servers.

In order to upgrade content databases I wrote small script which finds all content databases in the farm and upgrade them. Just run the UpgradeContentDatabase.ps1 script and PowerShell will do the rest. You will just have to verify upgrade for each content database. 

UpgradeContentDatabase.ps1

After upgrading content databases now we have to upgrade SharePoint servers. Microsoft recommends that first we need to upgrade Central Administration server, and after that web servers using PSConfig.exe command:

PSConfig.exe -cmd upgrade -inplace b2b -force -cmd applicationcontent -install -cmd installfeatures

And that's it, we have successfully implemented Cumulative Update on SharePoint farm. After that open Central Administration site and on Upgrade and Migration part go to Check Upgrade status and review upgrade. If there are no errors you are good to go. Also what I like to do is to go to Central Administration > Upgrade Migration > Review Database Status and check if status for all databases is No action required. 

Troubleshooting and rollback

Troubleshooting is a very broad theme, I can write whole new blog about it. My recommendation is a great blog by Samuel Betts http://ift.tt/1MDdRGw in which he explains most common issues and gives some initial pointers on where to start troubleshooting if it does happen.

If, for some reason, after upgrade you get correlation ID error best way to find what happened in log file is to merge logs and find actual error message:

- Open SharePoint PowerShell as Administrator

- Use Merge-SPLogFile –Path “C:\Error.log” –Correlation “ID here”

- Cmdlet grabs the ULS logs from all the servers in SharePoint farm

- Populates C:\Error.Log file with all instances of Correlation ID

- Open C:\Error.log file with ULS Viewer to see error associated with correlation ID

Sometimes, problem can be IIS. For instance, you can receive error that SharePoint service is unavailable due to a stopped IIS Application pool.

Best way for reviewing IIS logs is:

- Download and install Logparser or Log Parser Studio (https://http://ift.tt/1cBOpO4)

- Within Log Parser Studio, locate log file of interest in log directory, default location is %systemdrive%\inetpub\logs\LogFiles

- Execute pre-build query to view log file, or create new query

In case that you can not fix issues, or the downtime of SharePoint services is too long, you can start rollback procedure using server snapshots and database backups. I pointed out several times, but I will do it again: according to Microsoft this is not recommended action. However, when we are using snapshots with SharePoint, we need to not just snapshot a servers, a database, or a set of files… we are attempting to capture the state of the SharePoint farm at a point in time… and we need to capture that state in such a way that it is in perfect sync across all of the components. Shutting the machines down is a way to reduce the number of things that could be altering that state at any given moment, thereby increasing the likelihood that the capture of that state that we did will be a complete capture of that state, and that if we need to revert to that prior state, there are fewer things you need to accommodate, fix, or otherwise deal with that could make your farm completely unstable (and unsupportable).

So, the rollback should look something like this:

- Power down all SharePoint servers

- Restore all snapshots

- Restore all SharePoint SQL databases from backup

- Power on SharePoint servers

If all other procedures fail, last thing we can do is to restore SharePoint farm. There is a Technet article (http://ift.tt/1K4TRWu) which covers this procedure very well. Or you can use PowerShell Get-SPBackupHistory and Restore-SPFarm cmdlets:

(Get-SPBackupHistory -Directory <backup directory> -ShowBackup)[0].SelfId | Restore-SPFarm -Directory <backup directory> -RestoreMethod overwrite

This cmdlet gets all of the farm backup operations that have been run for the backup directory, finds the most recent backup, and then passes its backup GUID to the Restore-SPFarm cmdlet. The Restore-SPFarm cmdlet will then perform an overwrite restore from that backup package.

In the end, I think that is important to mention that you can use this steps if you are installing service pack on your SharePoint farm.

This concludes my long (and I am hoping not boring) blog regarding this important subject. Of course, there are lots of other themes I have not covered, like reducing downtime, using SharePoint 2013 Products Configuration Wizard, etc. I focused more on creating one document where you can find whole story, and don't have to, like me, go through bunch of Technet documentation and blogs, and try to assemble pieces into whole picture.


 


by Krsto Savic via Everyone's Blog Posts - SharePoint Community

Thursday, October 1, 2015

List all documents

Recently I had a task to create list of all documents uploaded in certain SharePoint site. Not a hard task you might think. But when you have dozens of libraries all containing hundreds of documents things are getting complicated.

So I created function called Get-Documents which helped me greatly:

function Get-Documents ()
    {
    Add-PSSnapin Microsoft.SharePoint.PowerShell
    $web = get-spweb (Read-Host "Enter Site URL")
        foreach ($list in $web.Lists)
            {
            if ($list.BaseType -eq "DocumentLibrary")
                {
                foreach ($item in $list.Items)
                    {
                    $data = @{
                
                                "Web" = $web.Url
                                "list" = $list.Title
                                "Item ID" = $item.ID
                                "Item URL" = $item.Url
                                "Item Title" = $item.Title
                                "Item Name" = $item.Name
                                "Item Created" = $item["Created"]
                                "Item Modified" = $item["Modified"]
                                "File Size" = $item.File.Length/1KB
                            }
                    New-Object PSObject -Property $data
                    }
                }
            $web.Dispose();
            }
    }

Get-Documents | Out-GridView
#Get-Documents | Export-Csv -NoTypeInformation -Path c:\temp\inventory.csv

Function takes all relevant (for me) information for each document from document libraries and put it in custom object.

Later you can take results and put it in grid view or export it to csv file.

 


by Krsto Savic via Everyone's Blog Posts - SharePoint Community

Wednesday, September 9, 2015

List all Access Request mail settings

The access request feature allows people to request access to content that they do not currently have permission to see. As a site owner, you can configure the feature to send you mail when someone requests access to a site. You can then choose whether to approve or decline their request. If you approve the request, you can also specify the specific level of permission you’d like to assign to a user.

However if your company have large amount of SharePoint web site it is very difficult to keep track whose e-mail address is configured to receive access requests.

This little script will help you list all access request configuration for one site collection:

# This script lists Access Request mail  for each site
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$site = Get-SPSite (Read-Host "Please enter site url")
foreach ($web in $site.allwebs)
{
 $url = $web.url
 $access = $web.RequestAccessEmail
 write-output "Web site is: $url; Access Request Mail is: $access"
}

SiteAccessRequestMailList.ps1


by Krsto Savic via Everyone's Blog Posts - SharePoint Community