Showing posts with label sharepoint. Show all posts
Showing posts with label sharepoint. Show all posts

Wednesday, January 4, 2017

PowerShell SharePoint to cancel workflows

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

$TargetWeb = "http://sharepoint/"
$TargetLibrary = "Library"
$Filename = 133 # the item ID
 
$MyWeb = Get-SPWeb $TargetWeb
$list = $MyWeb.Lists[$TargetLibrary]
$item = $list.GetItemById($Filename)

foreach ($wf in $item.Workflows) {
#Cancel Workflows      
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);    
}

WRITE-HOST "Discarded workflows"

Tuesday, January 3, 2017

SharePoint and PowerShell: Updating an individual user profile properties

When a user cannot be found from SharePoint central administration by going to Service Applications - User Profile Service - Manage User Profiles, it is likely that this user had some synchronization issues that is preventing detection from the UI.

In my situation the user was originally sync'd from Active Directory, but we had some OU changes and broke the hierarchy.
It's PowerShell to the rescue!

This example will retrieve a user profile from the web application, and updates the preferred name and user manager.

#Set up default variables
$mySiteUrl = "http://mysites"
$adAccount = "DOMAIN\username"
$upAttribute = "PreferredName"
$upAttributeValue = "My New Name"

#Get site objects and connect to User Profile Manager service
$site = Get-SPSite $mySiteUrl
$context = Get-SPServiceContext $site
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)

#Check to see if user profile exists
if ($profileManager.UserExists($adAccount))
{
    #Get user profile and change the value
    $up = $profileManager.GetUserProfile($adAccount)
    $up["PreferredName"]
    $up["Manager"]
    
    #$up["PreferredName"].Value = $upAttributeValue
    #$up.Commit()

    $up["Manager"].Value = "DOMAIN\manager"
    $up.Commit()
}
else
{
    write-host "Profile for user"$adAccount "cannot be found"
}


#Dispose of site object
$site.Dispose()

Wednesday, August 17, 2016

SharePoint online: Add site collection administrator using PowerShell

Prerequisites: You need Microsoft SharePoint Online Management Shell installed on your machine.

Script:

 $loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")  
 $loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")  
 $loadInfo3 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles")  
 #Must be SharePoint Administrator URL  
 $webUrl = "https://tenant-admin.sharepoint.com"  
 $username = "admin@tenant.onmicrosoft.com"  
 $password = "password"  
 $cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)  
 Connect-SPOService -Url $webUrl -Credential $cred  
 $site = Get-SPOSite -Identity https://tenant-my.sharepoint.com/personal/mysites_domain_com  
 Set-SPOUser -Site $site.Url -LoginName username@email.com -IsSiteCollectionAdmin $true  

Tuesday, February 2, 2016

PowerShell to upload a file into multiple sites under Project Web App (Office 365)

This is a powershell script custom written to upload an Excel report to multiple Project Online sites, but you could easily customize it to suit your own purposes. The same method works on Office 365 and SharePoint Online sites.

Prerequisites:
You will need to install the SharePoint 2013 client components on your client machine. I am running it on Windows 7 so I am actually using the PowerShell 64 bit version and 64bit client components.

 # Load SharePoint Client  
 Add-Type –Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"   
 Add-Type –Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"   

I am using the newest version on Project online, hence the 16 hive. 15 hive works as well!

SP2010 C# CSOM: Update Created and Modified dates and author

Tested on SharePoint 2010 only. I wanted to have something that could run on a client machine that could help update metadata for a folder or file in a list / document library.

This is a console application written in C#. Obviously, to do something in SharePoint 2010 automation, you will need to download the SP2010 foundation and install some runtime components.

(Or if you are feeling lazy, just copy Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll and reference them in your project).

To make this piece of code work, you need to know the ID of your list/folder item. There are other methods of retrieving based on URL.

Wednesday, January 13, 2016

PowerShell script to list and export top navigation links

This PowerShell snippet will parse a single site for the top or global navigation links, display in the shell window, and output to an XML file in the following format:

 <Navigation>  
 <Group Title="Regions" Url="http://regions">  
 <Link>  
      <Name>Asia Pacific</Name>  
      <Url>http://apac</Url>  
      <Target />  
 </Link>  
 <Link>  
      <Name>EMEA</Name>  
      <Url>http://emea</Url>  
      <Target />  
 </Link>  
 <Link>  
      <Name>US</Name>  
      <Url>http://us</Url>  
      <Target />  
 </Link>  
 </Group>  
</Navigation>  

Tuesday, October 20, 2015

PowerShell: SharePoint 2010 Add top/Global navigation links and sublinks

This works for SharePoint 2010 sites with the Publishing feature enabled.
Before getting started, populate the header, title and URLs in an XML file (I am saving this in a file called topNav.xml).

Sample format:

 <Navigation>  
      <Group Title="Sites">  
           <Link>  
                <Name>Asia Pacific</Name>  
                <Url>http://asiapac</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Canada</Name>  
                <Url>http://canada</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Europe</Name>  
                <Url>http://eu</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Japan</Name>  
                <Url>http://japan</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Penang</Name>  
                <Url>http://penang</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>United States</Name>  
                <Url>http://states</Url>  
                <Target />  
           </Link>  
      </Group>  
 </Navigation>  

And here is the powerShell script to grab the values and populate the Global Navigation section.

Thursday, October 15, 2015

PowerShell: Update target Audience of a SharePoint 2010 Web Part

 # Get reference to the SPSite object  
 $SPWeb = Get-SPWeb "http://sharepoint"  
 # Get reference to the landing page. Since it is a publishing site so default.aspx is the landing page   
 $page = $SPWeb.GetFile("Pages/index.aspx")   
 ### Uncomment the lines below to perform the update  
 #$page.CheckOut()   
 # //Get reference to the webpartmanager class   
 $webpartmanager = $SPWeb.GetLimitedWebPartManager("Pages/index.aspx", [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)    
 # Double check the web part that you wish to update. Iterate through webparts in webpartmanager class   
 for ($i=0;$i -lt $webpartmanager.WebParts.Count;$i++)   
 {    
      #write-host $webpartmanager.WebParts[$i].title  
      # Check for the name of required web part    
      if($webpartmanager.WebParts[$i].title -eq "Content Query Web Part")    
      {    
           #Get reference to the web part   
           $wp = $webpartmanager.WebParts[$i];   
           write-host $wp.title " " $i  
           # If there is any existing filter, copy it  
           write-host $wp.AuthorizationFilter  
           # In the filter (empty: ;;;;;;), first two semicolons: individual users as target audience; second two semicolons: distribution list; last two semicolons: can be replaced to include sharepoint groups    
           # e.g. "174e7e9d-ff39-4856-85a6-9247b02e59fb,124f1234-3998-4b54-83d1-abc4048fb9b4;;;;"  
           ### Optionally perform direct update while in for loop  
           # Other properties e.g. chrome property   
           #$wp.ChromeType="TitleAndBorder";   
           # Save changes to webpartmanager. This step is necessary. Otherwise changes wont be reflected   
           #$webpartmanager.SaveChanges($wp);   
  }    
  }    
 ### Uncomment the lines below to perform the update  
 #$wp = $webpartmanager.WebParts[26];  
 #write-host "begin update: " $wp.Title  
 #$wp.AuthorizationFilter = "174e7e9d-ff39-4856-85a6-9247b02e59fb,124f1234-3998-4b54-83d1-abc4048fb9b4,3a87dc31-9067-4996-b4c2-5efc6ff3eab7,68d2a840-bdbb-44ee-aacd-395b5551c473,7add71c2-dbea-4218-b8ff-f6b112f225e4,577550be-616e-41cd-90a4-493c030ddd72,9f113155-7c70-4d18-9417-851d82ba8b6a,c664006b-ec7f-4798-9acc-c48766be68a8,e26f7ece-615c-474d-9db9-0f60953e113a,ee912564-4f77-43c4-aced-55d387bc4e8e,51d2b9df-7ca3-42ad-a307-f9fdf28fe417,59500291-5912-47c0-b6a2-9c9adf24f2da;;;;";  
 #$webpartmanager.SaveChanges($wp);  
 #write-host "saving webpart target audience done...";  
 ### Uncomment the lines below to check in and Publish the page   
 #$page.CheckIn("Update Audience(batch powershell)")   
 #$page.Publish("Update Audience batch powershell)")   
 #$SPWeb.Update();    
 # Dispose SPWeb object   
 $SPWeb.Dispose();   

Wednesday, September 30, 2015

PowerShell list SharePoint Global Navigation headers and subheader links

This script will traverse the top navigation bar links in a SharePoint site and retrieve all the main headers plus dropdown links, and optionally list the link URLs.

Tried on SharePoint publishing sites.
How do you know if publishing is turned on?
If you see the Navigation link instead of Top Link Bar / Quick Launch, the feature is turned on.


Wednesday, September 9, 2015

SharePoint PowerShell: Adding complex rules to existing audience

Here is a PowerShell script to modify an existing Audience.

As you know, in SP2010, audience rules configured from the Central Administration can only have 2 choices:
1. Meet any condition listed
2. Meet ALL conditions listed

So if I want to have more complex conditions like nested conditions, I will either need to write a program (C#) to do it, or run some powershell commands in the web front end.

DO take note that once an audience is programmatically modified, you WILL NOT BE ABLE TO MAKE CHANGES from the Central Administation console anymore.

Sample script below:


Tuesday, June 23, 2015

SharePoint 2010 PowerShell: Batch assign permissions to each list item

PowerShell script to add permissions to all items in a list or library, where each item already has its unique set of permissions. Useful when you have hundreds of items in your library and can't be bothered to assign one by one.

Tuesday, June 16, 2015

SharePoint 2010 "Add to My Links" error: Page not found

Today I came across an interesting issue where users from a certain remote location were reporting a 'Page not found' error when trying to use 'Add to My Links' for documents stored under mysites.

Interestingly, the URL was malformed each time they attempted to click on the function.
It would end up looking like http://_vti_bin/portalapi.aspx?cmd=PinToMyPage&IconUrl=/_layouts/images/null&ListViewURL=xxxxxxxx 

Wednesday, June 3, 2015

SharePoint 2010 - Where are custom .acsx stored?

If you are developing visual webparts in SharePoint 2010 you may have wondered where the controls were stored.
It can be found in this folder in the 14 hive:
C:\Program Files\Common Files\microsoft shared\Web Server Extensions\14\TEMPLATE\CONTROLTEMPLATES\

However for SharePoint 2013 this is no longer valid as the ascx is generated on the fly from the compiled DLL.

Monday, February 23, 2015

SharePoint PowerShell - Set Site Collection Owner

Set-SpSite "http://sharepoint" -owneralias "DOMAIN\username"
Set-SpSite "http://sharepoint" -SecondaryOwnerAlias "DOMAIN\username2"

or alternatively, set the secondary site collection owner to null.

Set-SpSite "http://sp2010:90" -SecondaryOwnerAlias $null

Wednesday, February 11, 2015

SharePoint PowerShell: Recursively checkin files in a folder

This is a script that will try to parse a certain folder in a SharePoint 2010 site and recursively check for files that are checked out.
If found, the files would be checked in,

This is useful in situations where you are unable to move files and folders because someone had the files checked out.

Monday, December 1, 2014

SharePoint 2010: File locked for editing by xxx

In SharePoint 2010 it is very frequent to see users complaining of encountering this particular error when they try to edit a file in Office 2010 client.

It is because the SharePoint server will attempt to check every 10 minutes whether the user performing the edit still has the file handle open for editing.

According to the KB - waiting 10 minutes usually resolves the problem - http://support.microsoft.com/kb/899709

Sometimes, even though the user has checked in.closed the file after making his changes, other users still could not access the file for editing.

Wednesday, October 8, 2014

Developing SharePoint Visual Webparts: How to check if jQuery exist or is already loaded

When you try to create a SharePoint visual webpart that makes use of jQuery, it is generally known that any conflict will cause the javascript rendering to fail, e.g. any document.ready() function.

It is common when you have a lot of customized components that were activated as a feature.

You can easily check whether you have loaded conflicting versions of jQuery from viewing the source on the web page. But how do you control whether or not to load the jQuery if it already exists?

Solution:
Check whether the jQuery object can be created, before loading the .js file using javascript.
if (typeof jQuery == 'undefined') {
            var jq = document.createElement('script'); jq.type = 'text/javascript';
            // Path to jquery.js file
            jq.src = '/_layouts/Test/jquery.min.js';
            document.getElementsByTagName('head')[0].appendChild(jq);
        }

Tuesday, September 16, 2014

SharePoint powershell to cancel workflows

I got stuck into a situation where the workflows in SharePoint were stuck during the "In Progress" stage, and there was no way to cancel the workflow from the UI.

After googling around, I found a simple powershell solution and adapted it slightly to suit my needs.

The concept is very simple - Load the site, load the library, and either traverse all items, or retrieve a single item based on the ID. For that item, loop through the workflows and cancel it!

Tuesday, May 6, 2014

SharePoint 2010 Filter View by Quarter (Date)

This is an example of how you could create a view, with the help of calculated columns, to filter items in a SharePoint list by the quarter.

First, create 2 calculated columns of type Date and Time that will be the quarter start and quarter end of your preferred date.
e.g.
the date today: 5/7/2014 (Q2)
quarter start will be (1/4/2014) while quarter end will be 30/6/2014

Monday, May 5, 2014

SharePoint InfoPath 2010: C# populate rows in a repeating table

I had an InfoPath form where I needed to have 2 views. In the 2nd view, some information in the repeating table would be automatically populated based on the information entered in the first view.

Initially I wanted to use a rule-only approach but it ended up being too cumbersome; I had to resort to code :(

I will use a time card with date range as an example here. The repeating table will have one row for each day within the date range I have selected.

Related Posts Plugin for WordPress, Blogger...