Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Tuesday, March 4, 2014

Updating Permissions on List Items via PowerShell

The following script crawls all document libraries from a path of site and looks for *budget*.xls* and will replace all permissions on the Item with Read.
The script is useful to cut access for a pattern of files.

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

$site = get-spsite -identity "http://myspportal"

foreach($web in $site.AllWebs)
    {

    if ($web.Url.Contains("http://myspportal/HR/"))     # Look for only under HR
        {

        $Lists = $web.Lists | Where-Object {$_.Title -Like "*Reports*"}   # Pattern to look for in LISTS names
        $roleReadOnly = $web.RoleDefinitions["Read"]

        foreach($list in $lists)
            {
            
             foreach($item in $list.Items | Where-Object {$_.Name -like "*budget*.xls*"})     # Filename pattern is *budget*.xls*
                {
                Write-Host $item.ParentList.ParentWeb.Url+'/'+$item.URL + '      ' + $item.Name
                if ($item.HasUniqueRoleAssignments -eq $false)
                    {
                    $item.BreakRoleInheritance($true);
                    }

                foreach ($ra in $item.RoleAssignments | Where-Object {$_.RoleDefinitionBindings.Name -eq "Contribute" -or $_.RoleDefinitionBindings.Name -eq "Full Control" -or $_.RoleDefinitionBindings.Name -eq "Edit"})
                    {
                        $ra.RoleDefinitionBindings.RemoveAll()
                        $ra.RoleDefinitionBindings.Add($roleReadOnly)
                        $ra.Update()
                    }

                }
            }
        }
    }

Monday, January 6, 2014

Compress Old Files with PowerShell

The Story


The following PowerShell script will compress files that are older than the specified amount of time. It is handy for archiving IIS Logs, SQL Backups, etc.
The script uses 7-zip so you obviously have to have it installed (or the exe copied somewhere). It's using maximum compression which is resource intensive, if you don't want that just remove the "-mx9 -m0=lzma2" parameters.


The Script

$path = "C:\inetpub\logs\LogFiles\"
$mask = "*.log"

$days = 7

$files = dir $path -Recurse -Include $mask | where {($_.LastWriteTime -lt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)) -and ($_.psIsContainer -eq $false)}


ForEach ($file in $files) {

    & "C:\Program Files\7-Zip\7z.exe" u -mx9 -t7z -m0=lzma2 ($file.FullName + ".7z") $file.FullName
    if ($LASTEXITCODE -eq 0) {
        Remove-Item $file
    }

}

Resources

Wednesday, September 11, 2013

Set Permissions on Multiple Sites using PowerShell

These days I had a request to add an Active Directory group with Contributor rights on a SharePoint Site Collection. Since many sites had broken inheritance, using the UI was not an option so I created a small PowerShell Script that enumerates all Webs and if the Inheritance is broken, it adds the group with the specified Role.

Notes:


  • The If command uses the $web.Url.Contains directive in order to modify the rights only on a subset of sites. If all Webs have to be crawled, use if ($web.HasUniquePerm -and $web.RequestAccessEnabled) instead.
  • This script modifies permissions only on webs. Lists and Items with unique permission will not be touched.

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


$site = Get-SPSite -Identity "http://spdev/sites/SiteCollection"


foreach($web in $site.AllWebs)
    {

    if ($web.HasUniquePerm -and $web.RequestAccessEnabled -and ($web.Url.Contains("/SiteCollection/BU1") -or $web.Url.Contains("/SiteCollection/BU2")))
        {
            $account = $web.EnsureUser("Domain\QATeam")
            $role = $web.RoleDefinitions["Contribute"]

            $assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($account)
            $assignment.RoleDefinitionBindings.Add($role)

            $web.RoleAssignments.Add($assignment)
        }
    $web.Dispose()
    }
$site.Dispose()


References

Monday, September 9, 2013

SharePoint Start Workflow on All Items of a List via PowerShell

To start a List Workflow in SharePoint on All Items of a list is a pain through GUI but it's a piece of cake in PowerShell. Note that the Workflow will not start instantly (as opposed to triggering through the UI) but in maximum 5 minutes because it's started through the SharePoint Timer Service.


#updated on 10/17/2013

# URL of the Site
$web = Get-SPWeb -Identity "https://sharepointsrv/site1"

$manager = $web.Site.WorkFlowManager

# Name of the list
$list = $web.Lists["Shared Documents"]

# Name of the Workflow
$assoc = $list.WorkflowAssociations.GetAssociationByName("On Item Created","en-US")

$data = $assoc.AssociationData
$items = $list.Items
foreach($item in $items)
 {
 $wf = $manager.StartWorkFlow($item,$assoc,$data,$true)
 }
 
$manager.Dispose()
$web.Dispose()
#

References

Thursday, August 22, 2013

SharePoint 2013 Meeting Workspace Page Not Found

The Problem


I have some legacy Meeting Workspaces imported over from SharePoint 2010 that are still in use. Recently I enabled the Navigate Up button on a test site collection using this guide because users are really missing that feature. After applying the new master page to all subsites, I observed that the meeting workspace is no longer working. If I click on a meeting from a different date, a Page Not Found error is displayed on the site.


The logs:
 20635 08/22/2013 15:56:05.84   w3wp.exe (0x15D0)                         0x2EDC  SharePoint Foundation           Logging Correlation Data        xmnv  Medium    Name=Request (GET:https://spdevsrv:443/sites/dev1/WeeklyStatus/undefined?InstanceID=20130710&Paged=Next&p_StartTimeUTC=20130703T120000Z&View=%7bFEF87B6F%2d54D6%2d44CD%2d8055%2dFA404C0A5B50%7d)  57843b9c-4d5d-80a3-b6fd-c40b260782c1
 20636 08/22/2013 15:56:05.84   w3wp.exe (0x15D0)                         0x2EDC  SharePoint Foundation           Authentication Authorization    agb9s  Medium    Non-OAuth request. IsAuthenticated=True, UserIdentityName=0#.w|domain\user, ClaimsCount=43  57843b9c-4d5d-80a3-b6fd-c40b260782c1
 20637 08/22/2013 15:56:05.85   w3wp.exe (0x15D0)                         0x58E8  SharePoint Foundation           General                         af71  Medium    HTTP Request method: GET  57843b9c-4d5d-80a3-b6fd-c40b260782c1
 20638 08/22/2013 15:56:05.85   w3wp.exe (0x15D0)                         0x58E8  SharePoint Foundation           General                         af75  Medium    Overridden HTTP request method: GET  57843b9c-4d5d-80a3-b6fd-c40b260782c1
 20639 08/22/2013 15:56:05.85   w3wp.exe (0x15D0)                         0x58E8  SharePoint Foundation           General                         af74  Medium    HTTP request URL: /sites/dev1/WeeklyStatus/undefined?InstanceID=20130710&Paged=Next&p_StartTimeUTC=20130703T120000Z&View=%7bFEF87B6F%2d54D6%2d44CD%2d8055%2dFA404C0A5B50%7d  57843b9c-4d5d-80a3-b6fd-c40b260782c1
 20640 08/22/2013 15:56:05.85   w3wp.exe (0x15D0)                         0x58E8  SharePoint Foundation           Files                           aise3  Medium    Failure when fetching document. 0x80070002  57843b9c-4d5d-80a3-b6fd-c40b260782c1
 20641 08/22/2013 15:56:05.87   w3wp.exe (0x15D0)                         0x5198  SharePoint Foundation           Monitoring                      b4ly  Medium    Leaving Monitored Scope (Request (GET:https://spdevsrv:443/sites/dev1/WeeklyStatus/undefined?InstanceID=20130710&Paged=Next&p_StartTimeUTC=20130703T120000Z&View=%7bFEF87B6F%2d54D6%2d44CD%2d8055%2dFA404C0A5B50%7d)). Execution Time=37.2469  57843b9c-4d5d-80a3-b6fd-c40b260782c1


The Solution


You need to apply the mwsdefaultv15.master page to all Meeting Workspace sites. Since the SharePoint Server Publishing feature is not enabled (and cannot be enabled) on this type of site, you have to do the job in PowerShell.

$web =  Get-SPWeb -Identity "https://spdevsrv:443/sites/dev1"
$web.MasterUrl = "/sites/dev1/_catalogs/masterpage/mwsdefaultv15.master"
$web.CustomMasterUrl = "/sites/dev1/_catalogs/masterpage/mwsdefaultv15.master"
$web.Update()
$web.Dispose()

If you have a bunch of Meeting Workspaces then the script below might come in handy. For the sake of safety please back up your Site Collection first.

$site = Get-SPSite -Identity "https://spdevsrv:443/sites/dev1"
$webs = $site.AllWebs

$CorrectMasterPage = "/_catalogs/masterpage/mwsdefaultv15.master"

foreach($web in $webs)
 {
 if (($web.WebTemplate -eq "MPS") -and ($web.WebTemplateId -eq 2))
  {
  write-host "Updating" $web.Url
  $MasterPageURL = $web.ServerRelativeUrl + $CorrectMasterPage
  $web.MasterUrl = $MasterPageURL
  $web.CustomMasterUrl = $MasterPageURL
  $web.Update()
  }
 $web.Dispose()
 }

References


Find SharePoint Web Template Name using PowerShell

You can find out the Template Name and Id of a SharePoint Site using the following PowerShell command:

$web =  Get-SPWeb -Identity "http://spsrv/sites/web1/"
Write-Host $web.WebTemplate "," $web.WebTemplateId


To list all Template Names and IDs:

Get-SPWebTemplate | select ID, Name, Title | Sort-Object ID


References:

Tuesday, March 12, 2013

SharePoint PowerShell Create View Based on Existing View

The following PowerShell script crawls the specified lists, copies the fields from the All Items views and creates a new view named "Created By Me" and sets it as default. Tested with SharePoint 2010 but should work with 2013 as well. Tested with list but not with Document Libraries.

I used this script as a base.


$ver = $host | select version
if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"} 
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) 
{
 Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") 

$web = Get-SPWeb -Identity "http://portal/sites/Requests"
$lists=$web.Lists["User Request", "Hardware Request",  "Employee Request"]
$SourceView="All Items"
$NewViewName="Created By Me"
$NewViewDefault=$true


foreach($list in $lists) {

 $view = $list.Views[$SourceView]
 $Viewfields = $list.Views[$SourceView].ViewFields.ToStringCollection()
 $viewRowLimit="100"
 $viewPaged=$true
 $viewDefaultView=$NewViewDefault

# Setting the Query for the View
 $viewQuery = ""
 $viewName = $NewViewName

# Finally – Provisioning the View
 $myListView = $list.Views.Add($viewName, $viewFields, $viewQuery, 100, $True, $False, "HTML", $False)

# You need to Update the View for changes made to the view
# Updating the List is not enough
 $myListView.DefaultView = $True
 $myListView.Update()
 $list.Update()
}

$web.Dispose()