Wednesday, September 5, 2018

Start a workflow with Powershell - and pause for each item

This is one I use often.  It's pretty simple, but it allows me to start a workflow for all items in a list, and to wait between each item.  SharePoint is rickety - and delaying a kickoff of 400 workflows on 400 items is probably a good idea.  :)

Add-PSSnapin microsoft.sharepoint.powershell
# URL of the Site
$web = Get-SPWeb -Identity "http://somesharepointsite.com/sites/collection/subweb"
#Get workflow manager
$manager = $web.Site.WorkFlowManager
# Name of the list
$list = $web.Lists["Some SharePoint List"]
# Name of the Workflow
$assoc = $list.WorkflowAssociations.GetAssociationByName("Some Workflow","en-US")
$count = 0
$data = $assoc.AssociationData
$items = $list.Items
foreach($item in $items)
 {
    #Pause one minute between each workflow
    Start-Sleep -s 60
   
    #Fire the workflow for that item
    $wf = $manager.StartWorkFlow($item,$assoc,$data,$true)
 
    #Write to console that the workflow has fired
    write-host "Workflow fired for item: " $item.Name
 }
$manager.Dispose()
$web.Dispose()

Thursday, October 26, 2017

SiteServicesAddins.ReadFromPropertyBag: Site services addins don't exist for site collection

Oh man, this is an error that, when you see it, you'll be lost.  Here was out scenario:

Users would upload a document to a library in a Site Collection.  They would then try to tag that document with metadata.  We had four pieces of metadata, and the user would be able to tag them.

Then when the user clicked save, they would be told they don't have permission to update the document's properties, and two of the four metadata fields would not post. 

We would also see the following in the ULS logs:

CatalogConfig.ReadFromPropertyBag; Catalog configurations don't exist for site collection http://webapp/sites/collection

SiteServicesAddins.ReadFromPropertyBag: Site services addins don't exist for site collection http://webapp/sites/collection

At the same time, one of our admins recalled that they had deleted the Style Resource Readers group from the collection.

When that group is deleted, MANY BAD THINGS HAPPEN.  They are:

- Access Denied errors to a page
- Inability to browse menu items
- Inability to update metadata

So in our case, we re-created the Style Resource Readers group, gave NT Authority\Authenticated Users read permissions to the group, and made sure it had access to:

- The Style Library
- The Master Page Gallery
- The Site Assets Library

But still, we had the errors from above. 

After more digging, we found there is a list called the Hidden Taxonomy list that also is affected by this group.  This list holds Information Management Policy values when you set expiration on metadata.  The two fields the user couldn't update also happened to be fields that had expiration policies set on them.  So when SharePoint tried to invoke the policy to start it, the user didn't have rights to see what that policy was, hence the metadata was not applied.

That Hidden Taxonomy list lives at:  http://webapp/sites/collection/lists/hiddentaxonomylist

Once we went into that list and added the re-created Style Resource Readers group, we were back in business. 

The lesson here is be very careful who has Site Collection Admin rights, and make sure they speak loudly that they have maybe made a mistake.  It saved us a tremendous amount of time knowing a group was deleted that probably shouldn't have been. 

Then it was just an issue of finding something that was hidden. 

Wednesday, May 31, 2017

RBS ghosts in my house!

So let's say you deployed Remote Blob Storage for SharePoint.  Then later you decided you didn't want to deploy it for a particular content database and retracted the data from the blob back into the SQL content database.


Then later....maybe much later....uploads to your SharePoint site start failing.  Maybe it's after a Cumulative Update.  Maybe it's after a SQL upgrade.  You see the following in your ULS logs:

System.Runtime.InteropServices.COMException: The URL 'Documents/somedoc.docx' is invalid.  It may refer to a nonexistent file or folder, or refer to a valid file or folder that is not in the current Web.  


Failed in GetStreamInfo: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Microsoft.Data.SqlRemoteBlobs.RemoteBlobUsageException: The specified blob store <1> could not be found in the current database. 


What do you do?


There are a couple solutions that work for other people, then there's the solution that worked for us:


1.  Ensure Remote Blob Storage is set up correctly.  https://technet.microsoft.com/en-us/library/ee748631.aspx


2.  Ensure the Application Pool account that hosts the Web App where your Content Database lives has the correct RBS permissions.


For us, the fix was actually ensuring the Content Database that was no longer using RBS was ACTUALLY not using RBS.  It got confused, and we had to straighten it out with Powershell.  The script for the fix was fairly straightforward:

add-pssnapin Microsoft.SharePoint.Powershell


$cdb=get-SPContentDatabase some_content_database
$rbs=$cdb.RemoteBlobStorageSettings
$rbs.SetActiveProviderName("")


***

Using this, the Active Provider for RBS was disabled.  As soon as we ran this, we were then able to upload files without trouble to the SharePoint sites that were operating in that Content Database.


Hope this helps someone!

Friday, April 7, 2017

SharePoint 2013 High Trust Apps - 401 Unauthorized Error When Calling User Profile Service

When you call the User Profile Service in SharePoint 2013 from a High Trust App (or a SharePoint Add-In, as they're calling them now) some interesting things happen.  Consider the following scenario:


- You have an App that shows some data for a user via a CSOM call.  It's essentially a search of data that everyone at your company can see. 
- You also have, in the same App, a tab that shows information specific to that user, filtered by the user's location attribute in the User Profile Service. 


When the page loads, the first tab loads fine, since there are no calls.  The second tab, however, doesn't load anything.  You'll also get something like this in the Event log of your App Hosted server:


Source: System; Error: The remote server returned an error: (401) Unauthorized.; Stack Trace: at System.Net.HttpWebRequest.GetResponse()

at Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute()

at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)


This is the App Hosted server saying "Hey, I tried to talk to the User Profile Service, but I was denied."


There are a...LOT....of reasons why the User Profile Service might deny a request.  It could be the Application Pool account of the request doesn't have access to query the User Profile service application.  It could be SQL database permissions. 


One of the ways we found to help troubleshooting was to isolate the User Profile service to a Web Front End.  That is - we started the service on a web front end, and stopped it everywhere else.  (NOTE:  This is NOT the User Profile Synchronization Service.  Touch that not, else your life will suck in new, interesting ways).


Once the UPS was running on a web front end, we were able to see the request, and the reply in the same ULS log.  With that, we saw this:


SPJsonWebSecurityBaseTokenHandler: Issuer name in token '5924ce70-6ed4-4d21-913d-23b43664342d@1dd693ac-dfc1-434b-8eba-8758c2922b8e' doesn't match any of the registered issuer names for trusted sts 'SharePoint High-Trust App Tenant UAT'.

What does that mean?  It means the sts 'SharePoint High-Trust App Tenant' for UAT don't know nothin' about any app using an IssuerId of 5924ce70-6ed4-4d21-913d-23b43664342d.


We went to our App Hosted server, checked our web.config file for the App in question, and sure enough, the IssuerId in our <appSettings> section was wrong.  The settings looked like this:

<add key="IssuerId" value="5924ce70-6ed4-4d21-913d-23b43664342d" />


We checked a different App in the same farm, and saw this for its settings:


<add key="IssuerId" value="df6429b9-e397-4fb8-b0d2-0429a82d68a1" />


Once we swapped to the correct IssuerId, everything worked.


But why?  The why here is the High Trust Tenant is what enabled the App Hosted Servers, which are essentially just IIS servers, to be trusted by SharePoint.  If the Tenant doesn't have an IssuerId that matches what the App is saying its IssuerId is, it'll get blocked.


So in this case, User Profile was fine.  Application Pools were fine.  The App Model was fine. 


The lesson is:  Don't let a developer have access to your UAT farm - else he might decide his new App needs a brand new IssuerId, and set the entire farm's config for his lone App.  And you might not notice it until your App does something that requires elevated permissions. 

Wednesday, November 16, 2016

Powershell to delete User Profile Properties

This Powershell script will let you remove a specific User Profile property without having to use Central Administration.  This can be handy in a few different scenarios.

Script is:

Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$site = Get-SPSite "http://somesharepointsite.com"
$context = Get-SPServiceContext($site)
$upcm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileConfigManager($context)   
$cm = $upcm.ConnectionManager                
$pdtc = $upcm.GetPropertyDataTypes()
$ppm = $upcm.ProfilePropertyManager
$cpm = $ppm.GetCoreProperties()
$ptpm = $ppm.GetProfileTypeProperties([Microsoft.Office.Server.UserProfiles.ProfileType]::User)
$psm = [Microsoft.Office.Server.UserProfiles.ProfileSubTypeManager]::Get($context)
$ps = $psm.GetProfileSubtype([Microsoft.Office.Server.UserProfiles.ProfileSubtypeManager]::GetDefaultProfileName([Microsoft.Office.Server.UserProfiles.ProfileType]::User))
$pspm = $ps.Properties

# Remove User Profile Property by Name
$cpm.RemovePropertyByName("NAMEOFPROPERTYTODELETE")

Tuesday, October 4, 2016

Get all groups & members for a Site Collection

Add-PsSnapin Microsoft.SharePoint.PowerShell

$siteUrl = "http://somesite/sites/collection"
$web = Get-SPWeb $siteUrl

@(foreach ($group in $web.SiteGroups) {
  foreach($user in $group.Users) {
    $usergroup = New-Object System.Object
    $usergroup | Add-Member -type NoteProperty -name GroupName -value $group.Name
    $usergroup | Add-Member -type NoteProperty -name UserName -value $user.Name

     Write-Output $usergroup
    }
}) | Export-Csv c:\userlist.csv -NoTypeInformation

Thursday, August 11, 2016

Powershell to edit a SharePoint Web Application's web.config file

You really want to do this instead of directly editing the web.config file.  If you change the web.config directly, SharePoint won't know it's actually changed.  During the next patch or Config Wizard, SharePoint will overwrite the web.config with what it thinks should be there, which is bad.

For our purposes, we store the config changes in a csv file that Powershell will run.  That config file holds things like cache timeout settings for some of our custom apps, a custom branding url, and a switch for debug mode to be enabled for specific apps.

That config file can contain anything you might want, but it will need three columns.  They are:  Name, Owner, and Value

Ours looks like this:


Name Owner Value
app.DebugMode itsp FALSE
app.BrandingUrl itsp http://somesite.com/sites/common
app.Cache.CacheTimeout itsp 1
app.Cache.IsCacheEnabled itsp FALSE
app.Lists.EventsList itsp Events Calendar
app.Lists.ContactsList itsp Contacts
app.Lists.LinksList itsp Local Links
app.Lists.AssetsList itsp Site Assets


The Powershell is:

# Change this variable to the target Web App
$webAppUrl = "http://somewebapp.com"
$CSVLocation = "F:\Temp\ConfigMods.csv"


# Add Snapin if it is not already loaded
if ((Get-PSSnapin | ? {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null)
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

# Import configuration
$mods = Import-CSV $CSVLocation

$webApp = Get-SPWebApplication $webAppUrl

# Get the mods that need to be checked
$ownerstodelete = $mods | Group-Object owner | Select-Object Name

# For each mod
foreach($owner in $ownerstodelete)
{
    # Create an array
    $modstodelete = @()

    # For each current web mod
    foreach($mod in $webApp.WebConfigModifications)
    {
        # If mod is marked
        if($mod.Owner -eq $owner.Name)
        {
            # Add to the array
            $modstodelete += $mod
        }
    }

    Write-Host "Removing $($modstodelete.Count) web.config modifications from $($webAppUrl)" -ForegroundColor Yellow

    # Foreach mode to be deleted
    foreach($delmod in $modstodelete)
    {
        # Delete the mod
        $webApp.WebConfigModifications.Remove($delmod) > $null
        Write-Host " + Deleted mod $($delmod.Value)" -ForegroundColor Red
    }
}

# Reset sequence
$i = 0;

Write-Host ""
Write-Host "Adding $($mods.Count) web.config modifications to $($webAppUrl)" -ForegroundColor Yellow

# For each mod to add
foreach($modEntry in $mods)
{
    # Create the mod value
    $modValue = [system.string]::format(“<add key=""{0}"" value=""{1}"" />", $modEntry.Name, $modEntry.Value)

    # Create the mod object
    $mod = New-Object Microsoft.SharePoint.Administration.SPWebConfigModification
    $mod.Path = "configuration/appSettings"
    $mod.Name = [string]::Format("add[@key='{0}']", $modEntry.Name)
    $mod.Sequence = $i++
    $mod.Owner = $modEntry.Owner
    $mod.Type = 0
    $mod.Value = $modValue

    # Add the mod to the web app
    $webApp.WebConfigModifications.Add($mod)
    Write-Host " + Added mod $($modValue)" -ForegroundColor Cyan
}

# Update the web app
$webApp.Update()

# Apply web config changes
$webApp.WebService.ApplyWebConfigModifications()

# Run all Admin timer jobs
net stop SPAdminV4 > $null
Start-SPAdminJob
net start SPAdminV4 > $null

Write-Host ""
Write-Host "Web.config changes have been applied successfully" -ForegroundColor Green

Powershell to rename a Site Collection or change the Site Collection's managed path

This one will actually back up the named Site Collection, then restore it using the new managed path.  One thing most people don't mention is this won't necessarily put the Site Collection back in the same database it came from - so keep an eye on your databases in the Manage Content Databases area of Central Admin.  You want to be sure the Site Collection you're moving is in a content database that has enough Site Collections available before it hits a warning.  You also want to make sure you don't have another content db out there that has a much higher number of available slots.

SharePoint is lazy - and it'll go where the most room is.  Keep an eye on that.

Anyway, here's the script.

***

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue



#Get the Source Site Collection URL

$sourceURL = Read-Host “Enter the Source URL”

 

#Get the Target Site Collection URL

$targetURL = Read-Host “Enter the Destination URL”

 

#Location for the backup file

$backupPath = Read-Host “Where do you want the backup stored”



Try

{

  #Set the Error Action

  $ErrorActionPreference = "Stop"



 Write-Host "Backing up the Source Site Collection..."-ForegroundColor DarkGreen

 Backup-SPSite $sourceURL -Path $backupPath -force

 Write-Host "Backup Completed!`n"



 #Delete source Site Collection

 Write-Host "Deleting the Source Site Collection..."

 Remove-SPSite -Identity $sourceURL -Confirm:$false

 Write-Host "Source Site Deleted!`n"



 #Restore Site Collection to new URL

 Write-Host "Restoring to Target Site Collection..."

 Restore-SPSite $targetURL -Path $backupPath -Confirm:$false

 Write-Host "Site Restored to Target!`n"



 #Remove backup files

 Remove-Item $backupPath

}

catch

{

 Write-Host "Operation Failed. Find the Error Message below:" -ForegroundColor Red

 Write-Host $_.Exception.Message -ForegroundColor Red

}

finally

{

 #Reset the Error Action to Default

 $ErrorActionPreference = "Continue"

}



write-host "Process Completed!"

Tuesday, August 2, 2016

Forcing PDFs to open in the client in SharePoint 2013

So you want to have total control over how a PDF opens in SharePoint?  You're probably like me in that your implementation has Office Web Apps (OWA), and your organization is using Firefox, IE, maybe Safari and Chrome.

All these browsers have different ways of handling PDFs, with OWA having another method on top of all that.  But if you want to take advantage of signing / active forms in PDFs, you'll need to force SharePoint to use the Adobe client to open the files.

Luckily, there's an easy way to do this.  Javascript to the rescue.

First, take the Javascript below, save it as pdffix.js, and put it in the C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS directory of each Web Front End server on your farm:

(function () {

    if (typeof SPClientTemplates === 'undefined')

        return;



    var PdfCtx = {};

    PdfCtx.Templates = {};

    PdfCtx.Templates.Fields = { 'LinkFilename': { 'View': PdfClientLinkFilenameNoMenu } };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(PdfCtx);

})();



function GetExtension(szHref) {

    var sz = new String(szHref);

    var re = /^.*\.([^\.]*)$/;

    return (sz.replace(re, "$1")).toLowerCase();

}



var stsOpen = null;



function IsPdfClientInstalled() {

    if (stsOpen == null) {

        if (Boolean(window.ActiveXObject)) {

            try {

                stsOpen = new ActiveXObject("PdfFile.OpenDocuments");



            }

            catch (e) {

                stsOpen = null;

            }

        }

    }



    return (stsOpen != null);   

}



function OpenPdfInClient(pdfFileUrl) {   

    var fRet = true;



    try {

        fRet = typeof stsOpen.ViewDocument2 != "undefined" && stsOpen.ViewDocument2(window,

pdfFileUrl, '');

    }

    catch (e) {

        fRet = false;

    };



    if (event != null) {

        event.cancelBubble = true;

        event.returnValue = false;

    }



    return fRet;

}



function PdfNewGif(listItem, listSchema, ret) {

    if (listItem["Created_x0020_Date.ifnew"] == "1") {

        var spCommonSrc = GetThemedImageUrl("spcommon.png");



        ret.push("<span class=\"ms-newdocument-iconouter\"><img class=\"ms-newdocument-icon\"

src=\"");

        ret.push(spCommonSrc);

        ret.push("\" alt=\"");

        ret.push(Strings.STS.L_SPClientNew);

        ret.push("\" title=\"");

        ret.push(Strings.STS.L_SPClientNew);

        ret.push("\" /></span>");

    }

}



function PdfClientLinkFilenameNoMenu(param1, param2, listItem, listSchema) {

    var ret = [];

    var fileUrl = listItem.FileRef;



    if (fileUrl != null && typeof fileUrl != 'undefined' && TrimSpaces(fileUrl) != "") {

        if (listItem.FSObjType == '1') {

            if (listSchema.IsDocLib == '1') {

                RenderDocFolderLink(ret, listItem.FileLeafRef, listItem, listSchema);

            }

            else {

                RenderListFolderLink(ret, listItem.FileLeafRef, listItem, listSchema);

            }

        }

        else {

            ret.push("<a class='ms-listlink' href=\"");

            ret.push(listItem.FileRef);

            ret.push("\" onmousedown=\"return VerifyHref(this,event,'");

            ret.push(listSchema.DefaultItemOpen);

            ret.push("','");

            ret.push(listItem["HTML_x0020_File_x0020_Type.File_x0020_Type.mapcon"]);

            ret.push("','");

            ret.push(listItem["serverurl.progid"]);

            ret.push("')\" onclick=\"");



            var appInstalled = IsPdfClientInstalled();

            var szExt = GetExtension(listItem.FileRef);

            if (appInstalled && szExt == 'pdf' && browseris.ie) {

                ret.push("return OpenPdfInClient('");

                ret.push("http://");

                ret.push(window.location.hostname);

                ret.push(listItem.FileRef);

            }

            else {

                ret.push("return DispEx(this,event,'TRUE','FALSE','");

                ret.push(listItem["File_x0020_Type.url"]);

                ret.push("','");

                ret.push(listItem["File_x0020_Type.progid"]);

                ret.push("','");

                ret.push(listSchema.DefaultItemOpen);

                ret.push("','");

                ret.push(listItem["HTML_x0020_File_x0020_Type.File_x0020_Type.mapcon"]);

                ret.push("','");

                ret.push(listItem["HTML_x0020_File_x0020_Type"]);

                ret.push("','");

                ret.push(listItem["serverurl.progid"]);

                ret.push("','");

                ret.push(Boolean(listItem["CheckoutUser"]) ? listItem["CheckoutUser"][0].id :

'');

                ret.push("','");

                ret.push(listSchema.Userid);

                ret.push("','");

                ret.push(listSchema.ForceCheckout);

                ret.push("','");

                ret.push(listItem.IsCheckedoutToLocal);

                ret.push("','");

                ret.push(listItem.PermMask);

            }



            ret.push("')\">");



            var fileRef = listItem["FileLeafRef"];



            if (fileRef != null) {

                var index = fileRef.lastIndexOf('.');

                fileRef = index >= 0 ? fileRef.substring(0, index) : fileRef;

            }



            ret.push(fileRef);

            ret.push("</a>");



            PdfNewGif(listItem, listSchema, ret);

        }

    }

    else {

        ret.push("<nobr>");

        ret.push(listItem["FileLeafRef"]);

        ret.push("</nobr>");

    }



    return ret.join('');

}

****

Now, we Powershell.

Run the following Powershell commands, on a per-Library basis, to force PDFs to use this Javascript to open the files in the client. 

add-pssnapin microsoft.sharepoint.powershell

$web = Get-SPWeb http://somesharepointsite.com/sites/teamsite
$list = $web.Lists["My PDF Documents"]
$field = $list.Fields.GetFieldByInternalName("LinkFilename")
$field.JSLink = "/_layouts/15/PdfFix.js"
$field.Update($true)

***

Once that script runs, it'll be active.  No need to IIS reset or recycle application pools.

ONE IMPORTANT NOTE:  You're dumping customizations directly to the /15 hive.  This means Cumulative Updates / Service Packs will ALMOST CERTAINLY break this function.

We had the unfortunate experience of enabling this, then immediately patching to the May Cumulative Update the following weekend.  We had to re-run the Powershell script to re-enable the function (the .js file was not deleted).

Wednesday, May 25, 2016

When your MySite doesn't recognize you

So consider the following scenario:

Users log in to their MySites and are able to see their Profile and Newsfeed.  However, whenever they click on their Tasks link, they get redirected back to their Newsfeed.  It's almost as though SharePoint is treating them as a stranger to their own MySite.

We spun several hours on this problem, and I'm not sure our scenario fits for everyone.

The cause of our problem was we had migrated many thousands of MySites from one farm to a new farm.  We did this as part of a large scale farm upgrade.  When we did that, we did not backup and restore the User Profile databases.

Both farms were in the same domain, same usernames in Active Directory.  However, the rub came in the mismatch between the User Profile databases and the MySite content databases.

When a User Profile is imported from Active Directory, SharePoint assigns a GUID to that Profile and stores it in the User Profile database.  It then assigns that GUID to the MySite (in the MySites Property Bag) when the user first creates their MySite.

In our case, since the MySites were attached already, the creation action never fired.  And since the Profile GUID in the MySite Property Bag was different than the GUID in the Profile Database, when the user tried to click on their Tasks list, SharePoint didn't recognize them.

But there's a fix.  You can do this on a multiple site basis, or on an individual MySite basis.  The Powershell is:



$Web = Get-SPWeb http://[MySiteURL]/personal/[UserID]
$Web.SetProperty("urn:schemas-microsoft-com:sharepoint:portal:profile:userprofile_guid", "[NewGUID]")
$Web.Update()

 
You can get the NewGUID by querying UserProfileManager in PowerShell or by going to User Profile Service Application -> Manage User Profiles -> Find the user profile that is having issues -> Edit User Profile  

Then get the GUID out of the URL ProfAdminEdit.aspx?guid=[NewGUID] 

The credit for this one goes to Matt Coleman and Matt Royer - two of the guys on our team that dug pretty deep on this problem.  Hopefully it helps someone else out there.   

Thursday, May 12, 2016

Take ownership of SharePoint files with no checked in version, check them in, and publish with Powershell


This script will take ownership of all files in a library, then set whatever required metadata needs to be set, then check the items in.

Handy if a user has uploaded a ton of data using Explorer View, but never updated the metadata, and never actually checked in the files.  

if ((Get-PSSnapin | ? { $_.Name -eq "Microsoft.SharePoint.PowerShell" }) -eq $null) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

function BrowseItems($list, $Locationterm, $Departmentterm) {
    $files = $list.CheckedOutFiles
    foreach($file in $files)
    {
               $file.TakeOverCheckOut() #Take ownership of checked out document
    }


    foreach ($item in $list.Items) {
        $itemFile = $item.File

        if ($itemFile -ne $null) {
            if ($itemFile.CheckOutStatus -ne "None") {

                $LocationtaxField = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$item.Fields["GAC Location"]
                $DepartmenttaxField = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$item.Fields["GAC Department"]
                $fileName = $itemFile.Name
                $userName = $itemFile.CheckedOutByUser.Name;

                $item["Title"] = $fileName
                $LocationtaxField.SetFieldValue($item,$Locationterm)
                $DepartmenttaxField.SetFieldValue($item,$Departmentterm)
                $item.update()

               
                #Write-Host "Doing automatic CheckIn on the item" -f green -NoNewline
                $itemFile.CheckIn("Automatic CheckIn (Administrator)")
                #Write-Host " Done!" -f Yellow

                if( $list.EnableVersioning -and $list.EnableMinorVersions) {
                    #Write-Host "Doing automatic Publish on the item" -f green -NoNewline
                    $itemFile.Publish("Automatic Publish (Administrator)")
                    Write-Host "." -f Yellow
                }
            }
        }
    }
}

$url = "http://somesite.com/sites/teamsite/subweb"

$web = Get-SPWeb $url
$site = $web.Site

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

$session = New-Object Microsoft.SharePoint.Taxonomy.TaxonomySession($site)
$termStore = $session.TermStores[0]

$Locationgroup = $termStore.Groups["Locations"]
$LocationtermSet = $Locationgroup.TermSets["Location"]
$Locationterms = $LocationtermSet.GetAllTerms()
$Locationterm = $Locationterms | ?{$_.Name -eq "SomeCity"}

$Departmentgroup = $termStore.Groups["Departments"]
$DepartmenttermSet = $Departmentgroup.TermSets["Department"]
$Departmentterms = $DepartmenttermSet.GetAllTerms()
$Departmentterm = $Departmentterms | ?{$_.Name -eq "SomeDepartment"}

$list = $web.lists["Some Document Library"]

BrowseItems $list $Locationterm $Departmentterm

Thursday, May 5, 2016

Rename a List or Library in SharePoint 2013 with Powershell

Don't save the List or Library as a template, then restore it.  Use Powershell instead!

add-pssnapin microsoft.sharepoint.powershell

$libOriginalUrl = "/Lists/OldListURL/";
$libNewUrl = "/Lists/NewListURL";
$web = Get-SPWeb -Identity http://somesite.com/sites/teamsite

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

Thursday, April 14, 2016

Powershell to set all pages in a subsite to a specific Page Layout

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue



#Variables for Web and Page URLs

$WebURL="http://somesite.company.com/sites/collection/subsite"

$OldPageLayoutName="OldPageLayout.aspx"

$NewPageLayoutName="NewPageLayout.aspx"



#Get the web and page

$Web = Get-SPWeb $WebURL



#Get Publishing Site and Web

$PublishingSite = New-Object Microsoft.SharePoint.Publishing.PublishingSite($Web.Site)

$PublishingWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)



#Get New Page Layout

$SitePageLayouts = $PublishingSite.GetPageLayouts($false)

$NewPageLayout = $SitePageLayouts | ? {$_.Name -eq $NewPageLayoutName}



#Get Pages Library

$PublishingPages = $PublishingWeb.GetPublishingPages()



#Iterate throgh each page

foreach ($Page in $PublishingPages)

{


        $Page.CheckOut()

        $Page.Layout = $NewPageLayout

        $Page.ListItem.Update();

        $Page.CheckIn("Page layout Updated via PowerShell")

    

        #$page.ListItem.File.Publish("")

        if ($Page.ListItem.ParentList.EnableModeration)

        {

            $Page.ListItem.File.Approve("Publishing Page Layout Updated!");

        }



     write-host "Updated Page layout on: "$Page.url

  
}

$Web.Dispose()

Monday, March 21, 2016

Powershell to remove all alerts for a user in a Web Application

This script will delete all alerts for a specific user on a Web App.  It's useful when a user is deleted, but the MySite cleanup job did not remove their collection level alerts.

Credit on this one to:  http://www.sharepointdiary.com/2011/11/managing-alerts-using-powershell.html - Salaudeen Rajack. 
​
##### Remove all alerts for specific user from a Web Application #####
$SPwebApp = Get-SPWebApplication "http://somesharepointsite.com"
$SpecificUser = "AD\someuser"
foreach ($SPsite in $SPwebApp.Sites)
{ # get the collection of webs
foreach($SPweb in $SPsite.AllWebs)
{ $alerts = $SPweb.Alerts
# if 1 or more alerts for a particular user, Make a note of them by copying their ID to an Array
if ($alerts.Count -gt 0)
{ $myalerts = @()
foreach ($alert in $alerts)
{ if ($alert.User -like $SpecificUser)
{ $myalerts += $alert
}
}
### now we have alerts for this site, we can delete them
foreach ($alertdel in $myalerts)
{ $alerts.Delete($alertdel.ID)
write-host $alertdel.ID
}
}
}
}

Friday, March 18, 2016

Powershell to approve all items in a SharePoint list


This script will set all items in the list to Approved.  Handy if you've bulk updated a bunch of items than need to get them published.

add-pssnapin microsoft.sharepoint.powershell


#$site = new-object Microsoft.SharePoint.SPSite("http://somesite.com/news")

$web = get-spweb "http://somesite.com/news/2016/"
$list = $web.Lists["Pages to be Changed"]
$items = $list.Items
foreach ($item in $items)

{

$item["_ModerationStatus"] = 0
$item.Update()

}

Remove WWW prefix from SharePoint URLs

It's not every day you are tasked with doing something, with Microsoft in the room, and the Microsoft rep goes "Wow, we should totally put that on TechNet."

This is one of those things.

If you want to remove the www prefix from a url for all SharePoint sites, here's how:

1.  Download and install the URL Rewrite Module on all web front ends.  Get it here:  http://www.iis.net/downloads/microsoft/url-rewrite

2.  Configure Alternate Access Mappings in SharePoint to allow the www url.  We added an Internal URL for our WWW entry, and mapped it to the public url.  Our AAM settings looked like this when we were done:



3.  Add a binding in IIS for the additional WWW url.  Our bindings looked like this:



4.  Configure the URL Rewrite Module for the new address.  Do that by:
- Adding a Blank Rule
- Enter the pattern http://www.somesite.com/*
- Choose Rewrite for the Action Type
- Enter the pattern http://somesite.com/*
- Save it.

Why this works:

SharePoint needs an Alternate Access Mapping for the www url.  Once that's in place, IIS needs a binding to recognize the request from SharePoint.  Once THAT is entered, the rewrite module will see the www request come in, pick it up, and reroute it. 

The users will see the site automatically replace the URL to http://somesite.com.