Picture Library NavigationLink column value
Hi,
I have created a Sharepoint 2010 picture library. I have created a custom web part for image slider using this picture library.
I want to redirect user to NavigationLink URL of picture library item. I am using following code to get navigationlink URL:
using (SPSite site = new Microsoft.SharePoint.SPSite(SPContext.Current.Site.Url))
using (SPWeb web = site.OpenWeb())
SPList LstPicture = web.Lists[SLIDER_LIST];
SPQuery query = new SPQuery
Query = @"<Where>
<Eq>
<FieldRef Name='IsActive' />
<Value Type='Integer'>1</Value>
</Eq>
</Where>"
SPListItemCollection items = LstPicture.GetItems(query);
List<ImageCollection> lsts = new List<ImageCollection>();
foreach (SPListItem item in items)
string ImageUrl = Convert.ToString(item["ows_EncodedAbsUrl"]);
string ImageName = Convert.ToString(item["Name"]);
string Title = Convert.ToString(item["Title"]);
string Description = Convert.ToString(item["Description"]);
string IsActive = Convert.ToString(item["IsActive"]);
string NavigationLink = Convert.ToString(item["NavigationLink"]);
imageslist.Add(new ImageCollection(ImageUrl, ImageName, Title, Description, IsActive,NavigationLink));
Problem is it is giving me navigation link and desciption in item["NavigationLink"] field value. However I need only URL of the image. Which column of Picture library give me only Navigation URL without description.
Regards,
Amit
Hi,
Is Sudip's suggestion helpful to you?
Can you show what value retrieved in the "NavigationLink" field(screenshot would be better)? If you can get link and description all in once, then there
should be a method to extract the URL from it using C#.
Thanks
Patrick Liang
Forum Support
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support,
contact [email protected]
Patrick Liang
TechNet Community Support
Similar Messages
-
I have Library having metadata column when a document is uploaded i need update another list with metadata column of
library in list.I have an event reciever to do that,Code is given below
public override void ItemUpdated(SPItemEventProperties properties)
base.ItemUpdated(properties);
SPList saList = properties.Web.Lists["mylist"];
SPListItem item = saList.AddItem();
item["Department"] = properties.ListItem["Department"].ToString();
EventFiringEnabled = false;
item.Update();
EventFiringEnabled = true;
my elements.xml file is as below
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Receivers ListUrl="Documents">
<Receiver>
<Name>DocumentItemUpdated</Name>
<Type> ItemUpdated</Type>
<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
<Class>MyDocuments.Documents.Documents</Class>
<SequenceNumber>10000</SequenceNumber>
</Receiver>
</Receivers>
</Elements>
but i did not see the the List column getting updated.But when i use the code to update a column of single line of text
it works fine.But when i do it for multi select metadata column in debug mode i could see its giving null value even though Library had column value.
Any pointers on how to update Multiselect metadata column programatically on itemeadding event in library to a list will
be helpful.You need to use the TaxonomyFieldValueCollection class. The following code is from SP2010 but should still apply in SP2013. It is an example of updating multivalued taxonomy fields.
public static void SetListItemMultiMetaDataColumn(Int32 id)
using (SPSite site = new SPSite("http://basesmc2008"))
using (SPWeb web = site.OpenWeb())
TermSet termSet = null;
TaxonomySession txs = new TaxonomySession(site);
SPList list = web.Lists["Shared Documents"] as SPList;
SPListItem item = list.GetItemById(id);
TaxonomyField field = item.Fields["multimanage"] as TaxonomyField;
if (field != null)
termSet = txs.DefaultSiteCollectionTermStore.GetTermSet(field.TermSetId);
Term term = termSet.GetTerms("sts", false).FirstOrDefault();
if (field.AllowMultipleValues)
TaxonomyFieldValueCollection currentCollection = item[field.Id] as TaxonomyFieldValueCollection;
TaxonomyFieldValue tfv = new TaxonomyFieldValue(field);
tfv.TermGuid = term.Id.ToString();
tfv.Label = term.GetPath();
tfv.WssId = TaxonomyField.GetWssIdsOfTerm(site, txs.DefaultSiteCollectionTermStore.Id, termSet.Id, term.Id, false, 1).First();
currentCollection.Add(tfv);
field.SetFieldValue(item, currentCollection);
item.Update();
Blog |SharePoint Field Notes Dev Tool |
SPFastDeploy -
Doc library - 3 columns of type Hyperlink or Picture - one of them suddenly doesn't work
Hi
I have a doc. library with various columns (metadata) - 3 of them is of the type "Hyperlink or Picture".
Suddenly, I'm not able to insert a link in one of them. When clicking 'OK' - I return to doc.library, and the link is not there. No errors. Nothing. I'm able to test the link - and also able to insert the same link in one of the other "Hyperlink or
Picture" columns.
Can anyone help?
Best regards,
HasseHi,
Columns of type Hyperlink or Picture are used to store a hyperlink to a Web page or to display a graphic on the intranet or Internet.
Does your Columns with the same Format URL? Hyperlink or Picture?
If your column is with Picture Format URL, you can't directly add picture into "Hyperlink or Picture" column because this column takes URL value and image is binary etc. You can first upload that picture into picture library (create new picture
or document library) then add that image link into that column.
Besides, I suggest you create a new document library with the same 3 columns of type Hyperlink or Picture and compare the results. if the issue doesn't exists in other library, you can delete the issue column and create a same column in the document library.
Best regards,
Lisa Chen
TechNet Community Support
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
[email protected] -
Get/retreive managed metadata column value from Document Library using SharePoint 2013 JSOM
Hi,
I am trying to retrieve managed metadata column (NewsCategory) value in SharePoint 2013 Document library using JSOM.
I get "Object Object" rather than actual value.
I tried:-
var newsCat = item.get_item('NewsCategory');
alert(newsCat) //Displays [Object Object]
var newsCatLabel = newsCat.get_label();
var newsCatId = newsCat.get_termGuid();
But, I get the error "Object doesn't support property or method get_label()"
I also tried :-
var newsTags = item.get_item(' NewsCategory ');
for (var i = 0; i < newsTags.get_count() ; i++) {
var newsTag = newsTags.getItemAtIndex(i);
var newsTagLabel = newsTag.get_label();
var newsTagId = newsTag.get_termGuid();
Even now I get the error "Object doesn't support property or method get_count()"
I have included " NewsCategory " in the load request:- context.load(items, 'Include(File, NewsCategory)');
Any idea what the issue is? Do I have to add any *.js file using $.getScript?
I added following .js files
var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.Runtime.js", function () {
$.getScript(scriptbase + "SP.js", function () {
$.getScript(scriptbase + "SP.Core.js", function () {
Thanks in Advance,Hi Patrick,
I already added those references. I just pasted the parts of script snippet in my initial post. To avoid confusion I am pasting here complete script.
2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.Runtime.js", function () {
$.getScript(scriptbase + "SP.js", function () {
$.getScript(scriptbase + "SP.Core.js", function () {
function getdata() {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('Documents');
var camlQuery = new SP.CamlQuery();
var filterCategory = 'Solutions';
var IDfromTaxonomyHiddenList = 15;
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef LookupId="TRUE" Name="'+filterCategory+'" /><Value Type="ID">' + IDfromTaxonomyHiddenList +'</Value></Eq></Where></Query></View>');
/*the above CAML query successfully gets all the list items matching the criteria including "NewsCategory" managed metadata column values
But when I try to display the value it retrieved it ouputs/emits Object Object rather than actual values */
var items = list.getItems(camlQuery);
context.load(items, 'Include(File,NewsCategory)');
context.executeQueryAsync(
Function.createDelegate(this, function (sender, args) {
if (items.get_count() > 0) {
var listItemEnumerator = items.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var file = oListItem.get_file();
var name = file.get_name();
var newsCat = oListItem.get_item('NewsCategory'); alert(newsTags.constructor.getName());
alert(newsCat) //Displays [Object Object]
var newsCatLabel = newsCat.get_label(); // Here it errors out with message "Object doesn't support property or method get_label()"
var newsCatId = newsCat.get_termGuid();
} //end while
}//end if
Function.createDelegate(this, function (sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
ExecuteOrDelayUntilScriptLoaded(getdata, "SP.Core.js");
</script>
In the above script "var name = file.get_name(); " gets the exact file name.
But the line "var newsCat = item.get_item('NewsCategory');
alert(newsCat) //Displays [Object Object] rather than actual value.
Issue resolved replace "oListItem.get_item('NewsCategory');" with oListItem.get_item('NewsCategory').get_label();"
Thanks -
Hi,
I have created a custom web part to show image slider from SharePoint picture library. SharePoint stores various size image in different columns of picture library.
I am using below code to get image URL. Which column should I use to display full size image in image slider.
string ImageUrl = Convert.ToString(item["ows_EncodedAbsUrl"]);
Regards,
AmitAmit, try ows_EncodedAbsThumbnailUrl
string ImageUrl = item["ows_EncodedAbsThumbnailUrl"].ToString();
Refer Link -
https://social.msdn.microsoft.com/Forums/en-US/85e345a2-181c-4ca0-894c-ca9c3ef8b838/how-to-bind-the-image-from-the-sharepoint-list-in-gridview-using-vs-2010-as-webpart?forum=sharepointdevelopmentprevious
https://alexdinnouti.wordpress.com/2013/09/14/sharepoint-2007-photo-library-and-shadowbox/
http://galratner.com/blogs/net/archive/2011/02/27/send-a-web-page-as-an-email-with-embedded-images.aspx
http://debugmode.net/2011/02/07/fetching-image-from-sharepoint-2007-picture-library-using-object-model/
Please 'propose as answer' if it helped you, also 'vote helpful' if you like this reply. -
Hello,
I am facing a wired issue with Picture Libraries in SharePoint.
We created a custom field and added it to UserInfo list, the column based on custom field lets user upload their personal images to a Picture Library with the name <User ID>.<Image Extension> e.g. 1.jpg where UserID is internal Listitem ID of the UserInfo list and set its URL to the field value which we use to display the image on our custom user profile and some other WebParts.
If the user uploads a different image, it will overwrite the existing one it keeping the same name.
The field worked perfectly with sites using widows Based authentication, but as we move the field to sites with form based authentication we find that the field is able to upload the image properly first time but on each successive upload, although a new image gets uploaded with the name userid.imagextension and is shown in the allitems.aspx page in the thumbnail view and in the picture preview on the dispform.aspx page, but the link next to the name field and the image shown on clicking the preview points to the old image.
To put it other way
https://<Web URL>/Picture%20Library/_w/Upload_jpg.jpg
https://<Web Url>/Picture%20Library/_t/Upload_jpg.jpg
Would show the updated image
but the actual URL
https://<Web Url>/Picture%20Library/Upload.jpg
points to the old image
what’s even more strange is that even after deleting the image the url still shows the old image at
https://<Web Url>/Picture%20Library/Upload.jpg
I confirmed the same by actually repeating the same exercise on a picture Library in the User Interface
Uploading an image say upload.jpeg in the picture library using SharePoint interface.
Then uploading a different jpeg image keeping the same name upload.jpeg again in the picture library.
In allitems.aspx thumbnail view and on dispform.aspx page preview filed image now show the newly uploaded image but when you click the preview image or click the link in the name field value it takes you back to the old image.
I have seen this issue on environment where we have enabled form based authentication and the issue is not seen on another server where we have wss with windows based authentication.
Has anyone noticed such behavior and is there any workaround to that!
Thanks & Regards
Saurabh RustagiAll,
I had the same issue.
In my case, Blob Cache was enabled for the web application in which the image issue was occuring.
I cleared blob cache, and after doing a hard refresh of my browser, the correct image was then displayed.
To clear blob cache, do the following:
Navigate to:
http://yourwebapp:port/yoursite/_layouts/objectcachesettings.aspx
Select: "Object Cache Flush" and "Force all servers in the farm to flush their object cache" check boxes
Click the OK button
Hope this helps. -
How to get column values on item added event receiver
Hi,
I have two columns in a document library and one is people or group column and the other one is choice column with check boxes.
I want to know how to read column values on Item Added event receiver, so that I can create if statements based on those values.
Thank you,
AA.Hi AOK2013,
Have you had a look at this Microsoft tutorial: http://msdn.microsoft.com/en-us/library/office/gg981880(v=office.14).aspx
Essentially, you want to use the AfterProperties property to access the changed field value.
E.g.
var personvalue = properties.AfterProperties["YourPersonFieldName"]
Regards, Matthew
MCPD | MCITP
My Blog
View
Matthew Yarlett's profile
See my webpart on the TechNet Gallery that allows administrative users to upload, crop and format user profile photos. Check it out here:
Upload and Crop User Profile Photos -
Hi Everyone
I don't know if this is possible or not, so I will describe it. I have a column in a table called Filing. There are currently three values in it ("Abuse", "Neglect", "Voluntary") and each record has this populated. I also have
the below slicer for the column also.
I would like to add a fourth value called "Abuse/Neglect" that would identify instances where both an Abuse and Neglect petition was filed, which is a subset of the Abuse and Neglect records in the Filing column.
My question is, is it possible to create a line chart that has the 4 Filing possibilities: "Abuse", "Neglect", "Voluntary", "Abuse/Neglect" as the Series/Legend in the line chart?
The problem is that there are records that are more than one category: Abuse or Neglect records can also be Abuse/Neglect.
PaulHi Paul,
According to your description, there is a column with the values ("Abuse", "Neglect", "Voluntary") in your table, now what you need to is that add another value "Abuse/Neglect" in this column, and then use it
as Series/Legend in the line chart, right?
In this case, you can add calculated column to your table based on your logic. A calculated column is a column that you add to an existing PowerPivot table. Instead of pasting or importing values in the column, you create a DAX formula that defines
the column values. The calculated column can be used in a PivotTable, PivotChart, or Power View report as you would any other data column. Please refer to the link below to see the details.
https://msdn.microsoft.com/en-us/library/gg413492%28v=sql.110%29.aspx?f=255&MSPPError=-2147217396
Regards,
Charlie Liao
TechNet Community Support -
Hi,
We have created a SharePoint site column with below settings
1. ShowInEditForm - False
2. ShowInNewForm - False
3. ShowInDisplayForm - True
With the above definition, the site column showing only in view properties form not in New and Edit forms. This column is added to a document library and updating this column value will be managed by event receiver code when a document is uploaded.
Till this point, everything is working OK.
But the issue is when we download and open a document from the above document library, under document properties the above column (with value) is visible along with other document default properties and this column value is editable. With this issue,
user is able to set a new value and overwrite the existing value by re-uploading the document.
Could you please let me know how to handle this issue so that user should not be allowed to edit except viewing the value/property (read only)?
Thanks in advance.
Regards
RameshYou can set "ShowInFileDlg" property of field to "FALSE". Using this you will not see that field in document properties list
-
Hi All,
I have a picture library with images in sharePoint, now i want display that images in sharepoint webpage as a webpart.
i have displayed the all the images as a webpart.
Now i want to enable thumbnail on that images and when i click the thumbnail of the image, it will be dilplayed as large image.
How can i do this, any help!Hi,
Please do the following to complete this task.
1) Insert the picture library as list view webpart in your page.
2)Specify the column titled Thumbnail Preview in the list view.
3) Edit the webpart and set the Toolbar Type to Summary Toolbar.
Regards,
Anurag -
Update a list item based sort order of created by column value
HI
using powershell script how to sort a list column before update a list item.
here i created a document library and uploaded some documents and update ProcessNo column based sort order of created column
value.
Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
$webURL = "http://tspmcwfe:91" $listName = "Courts"
Get the SPWeb object and save it to a variable
$web = Get-SPWeb $webURL
$list = $web.Lists[$listName]
$items = $list.items
Go through all items
foreach($item in $items)
$item["ProcessNo"] = 1
$item.Update()
$web.Dispose()Hi,
According to your description, my understanding is that you want to sort the list items order before updating items using PowerShell.
I suggest you can use the Sort-Object command to sort the list items.
Here are some detailed articles for your reference:
Better SharePoint Lists and List Items in PowerShell
Sort-Object
Thanks
Best Regards
TechNet Community Support
Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
[email protected] -
Hi,
We have a requirement to update a column value once the item has been approved.
Following settings have been made in the publishing articles list:
Require content approval for submitted items : yes
Create major and minor (draft) versions
Who should see draft items in this document library? :Only users who can edit items
Require documents to be checked out before they can be edited? : yes
I have createdatu a Sharepoint 2013 workflow to check if Approval sts of current item = 0 i.e. Approved , then check out and update the item and finally checkin the item. Everything works fine till this point except that the minor version of the item is
checked in. Due to this the updated columns are not published to others.
Also, I created a Sharepoint 2010 workflow to SET CONTENT APPROVAL = APPROVED and started this workflow from my list workflow above, but the item does not get checked-in and always shows "In Progress" status with comment "The item is currently
locked for editing. Waiting for item to be checked in or for the lock to be released.".
Please let me know where I am missing out so that once the item is approved, column value gets updated and current item is still in Approved status.
ThanksHi,
According to your post, my understanding is that you want to update Column value after current item is Approved and then publish major version using Sharepoint 2013 designer workflow.
You will get into this kind of Catch-22 situation trying to set the Content Approval Status in SharePoint Designer workflow:
- You must check out the document before you can change the Content Approval Status
- You can't change the Content Approval Status once the document in checked out
Since you set the Require documents to be checked out before they can be edited=Yes, you will need to check out the document when run the workflow on the item. But you cannot approve a document when it is checked
out. So the logic in workflow conflicts.
As a workaround, you can use the Start Another Workflow action to start the normal Approval workflow on the document. The built-in Approval workflow can work with a document that’s not checked out.
The designer approval workflow also can work with a document that’s not checked out.
You can create two workflow using SharePoint Designer 2013.
First, create a SharePoint 2010 platform workflow.
Then, create a SharePoint 2013 platform workflow.
Then when the SharePoint 2013 platform workflow start, it will start the SharePoint 2010 platform workflow to set content approval status, then the SharePoint 2013 platform workflow will update current item value.
More information:
SharePoint Designer Workflow Content Approval Issue
SharePoint 2010 Approval Workflow with Content Approval
Best Regards,
Linda Li
Linda Li
TechNet Community Support -
Picture Library Slideshow Web Part
I am able to create a slide show via Picture Library Slideshow Web Part but the title and description will not show up. I have tried all the options but
only the picture shows and not the picture title. I was hoping to have the picture title appear below the image. Can this be fixed or is it something I have to do without?
Thank you.Hi Sarah,
According to your description, my understanding is that you want to show Title of the image under the image in Picture Library Slideshow Web Part.
I recommend to edit the Picture Library Slideshow Web Part and select Title only below image under Display with and make sure that the picture in the picture library has value in Title field.
Best regards.
Thanks
Victoria Xia
TechNet Community Support -
It looks like whenever one specifies Column default values at a library level then the content organizer routing goes a bit awry SPECIFICALLY FOR NON OFFICE FILES [e.g. PDF] . Below are the observations and issues
1. Column level default value set on a record library with auto declaration of records turned on. The content organizer routes the document to the library but also keeps a copy of the document in the drop off library. It does not remove it from the drop
off library. The instant we clear the default value settings at the library level of the target library the content organizer works as expected again.
2. If default value settings are specified on a column in the target library then the PDF file gets routed to the document library but all the metadata is blanked out. The copy of the file that remains in the drop off library has all the correct metadata but
the target library has blanked out metadata.
Are the 2 observations described above by design or are they bugs? If so is there any documentation that is available that proves this because this does not make logical sense and proving this to a client in the absence of any documentation is a challenge.
The problem goes away if we shift the default value to the site columns directly at the site collection level. It's just the library level defaults that the pdf files do not seem to agree withHi Lisa,
Thanks for responding. This can be replicated in any environment but is only replicable for a specific combination of content organizer settings . The combination of settings I am referring to can be seen in the screenshot below. If you turn off redirect
users to the drop off library for direct uploads to libraries and if you turn on sharepoint versioning then you should be able to replicate the issue. Also we are using managed metadata site columns. I simplified this use case to a custom content content type
with just 2 custom managed metadata columns and can still replicate the issue in several environments. Also note the issue does not occur if the default values are set at the site or site collection level. It only occurs if you set the column value default
at a library level. I was able to replicate this on a completely vanilla Enterprise records site collection freshly created just to test this. Also note that the issue is not that the file does not reach the destination library. The issue is the
document does not get removed from the drop off library after it is transfered to the destination library which technically should have gotten removed. -
How to refresh/apply column value default setting on current files or folders
Hi All
I have set-up default column data per folder in my library (via
Library Settings > Column default settings) and it works great for new documents or folders that are added to the library.
But what do I do if I have an existing Library with folders and files and need to apply default column data to each? Is there a way of "refreshing" the default columns so that the data is populated through a specific folder and/or its sub-folders?
(I really hope this is an easy fix or just a setting that I over-looked somewhere!)
Thank you!I had to do this as well recently, and remembered your post.
Here is the function I wrote , this worked for text, choice, and metadata columns
It is pretty slow and could be optimized and broken up into more functions, but I had to do several things:
1. I mass-updated the content types in a library
2. On Library settings : set default values and also different defaults per folder
3. For each file I then needed to:
3.a. either copy the value from a column in the old content type to the new, or
3.b. set the column to the default
so this function does step 3, like I said it works for certain types of columns and can be sped up (I used it to update 700 files in a couple minutes), and it makes some assumptions about the environment but this at least is a starting point.
As Alex said you may want to change SystemUpdate($true) to just Update(), depending on your requirements.
<#
.SYNOPSIS
Resets columns in a document library to defaults for blank columns. Use this
after changing the content types or adding columns to a doc lib with existing files
.DESCRIPTION
Resets columns in a doc lib to their defaults. Will only set them if the columns are blank (unless overridden)
Will also copy some values from one column to another while you are there.
Can restrict the update to a subset of columns, or have it look for all columns with defaults.
Will use the list defaults as well as folder defaults.
All names of columns passed in should use InternalName.
This has ONLY been tested on Text, Choice, Metadata, and mult-Choice and Mult-Metadata columns
Pass in a list and it will recursively travel down the list to update all items with the defaults for the items in that folder.
If you call it on a folder, it will travel up the tree of folders to find the proper defaults
Author:
Chris Buchholz
[email protected]
@plutosdad
.PARAMETER list
The document library to update. Using this parameter it will update all files in the doc lib
.PARAMETER folder
The folder containing files to update. Function will update all files in this folder and subfolders.
.PARAMETER ParentFolderDefaults
Hashtable of internal field names as KEY, and value VALUE, summing up all the parent folders or list defaults.
If not supplied, then the function will travel up the tree of folders to the parent doclib to determine
the correct defaults to apply.
If the field is managed metadata, then the value is a string
Currently only tested for string and metadata values, not lookup or date
.PARAMETER termstore
The termstore to use if you are going to update managed metadata columns, this assumes we are only using the one termstore for all columns to update
If you are using the site collection specific termstore for some columns you want to update, and
the central termstore for others, then you should call this method twice, once with each termstore,
and specify the respective columns in fieldsToUpdate
.PARAMETER fieldsToCopy
Hashtable of internal field names, where KEY is the "to" field, and VALUE is the "from" field
Use this to copy values from one field to another for the item.
These override the defaults, and also cause the "from" (Value) fields to NOT be overwritten with defaults even if
they are in the fieldsToUpdate array.
Example: @{"MyNewColumn" = "My_x0020_Old_x0020_Column"}
.PARAMETER fieldsToUpdate
If supplied then the method will update only the fields in this array to their default values, if null then it will update
all fields that have defaults.
If you pass in an empty array, then this method will only copy fields in the fieldtocopy and not
apply any defaults
Example: @() - to only copy and not set any fields to default
Example2: @('UpdateField1','UpdateField2') will
.EXAMPLE
Set-SPListItemValuesToDefaults -list $list -fieldsToCopy @{"MyNewColumn" = "My_x0020_Old_x0020_Column"} -fieldsToUpdate @() -overwrite -termStore $termStore
This will not set any defaults, but instead only set MyNewColumn to non null values of My_x0020_Old_x0020_Column
It will overwrite any values of MyNewColumn
.EXAMPLE
Set-SPListItemValuesToDefaults -list $list -overwrite
This will set all columns to their default values even if they are filled in already
.EXAMPLE
Set-SPListItemValuesToDefaults -folder $list.RootFolder.SubFolder[3].SubFolder[5]
This will set all columns to their defaults in the given subfolder of a library
.EXAMPLE
Set-SPListItemValuesToDefaults -list $list -fieldsToUpdate @('ColumnOneInternalName','ColumnTwoInternalName')
This will set columns ColumnOneInternalName and ColumnTwoInternalName to their defaults for all items where they are currently null
.EXAMPLE
Set-SPListItemValuesToDefaults -list $list -fieldsToCopy @{"MyNewColumn" = "My_x0020_Old_x0020_Column"} -fieldsToUpdate @("MyNewColumn") -termStore $termStore
This will set all MyNewColumn values to their default, and then also copy the values of My_x0020_Old_x0020_Column to MyNewColumn where the old column is not null,
but both of these will only happen for items where MyNewColumn is null
.EXAMPLE
Set-SPListItemValuesToDefaults -list $list -fieldsToCopy @{"MyNewColumn" = "My_x0020_Old_x0020_Column"} -termStore $termStore
This will set ALL columns with defaults to the default value (if the item's value is null),
except for My_x0020_Old_x0020_Column which will not be modified even if it has a default value, and will also set MyNewColumn to the
value of My_x0020_Old_x0020_Column if the old value is not null
#>
function Set-SPListItemValuesToDefaults {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="List")][Microsoft.SharePoint.SPList]$list,
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="Folder")][Microsoft.SharePoint.SPFolder]$folder,
[Parameter(Mandatory=$false,ParameterSetName="Folder")][HashTable]$ParentFolderDefaults,
[Parameter(Mandatory=$false)][HashTable]$fieldsToCopy,
[Parameter(Mandatory=$false)][Array]$fieldsToUpdate,
[Parameter(Mandatory=$false)][Microsoft.SharePoint.Taxonomy.TermStore]$termStore,
[Switch]$overwrite,
[Switch]$overwriteFromFields
begin {
#one or both can be null, but if both empty, then nothing to do
if ($null -ne $fieldsToUpdate -and $fieldsToUpdate.Count -eq 0 -and
( $null -eq $fieldsToCopy -or $fieldsToCopy.Count -eq 0)) {
Write-Warning "No fields to update OR copy"
return
if ($PSCmdlet.ParameterSetName -eq "Folder") {
$list = $folder.DocumentLibrary
if ($null -eq $termStore ) {
$taxonomySession = Get-SPTaxonomySession -site $list.ParentWeb.Site
$termStores = $taxonomySession.TermStores
$termStore = $termStores[0]
#if we did not pass in the parent folder defaults then we must go backward up tree
if ($PSCmdlet.ParameterSetName -eq "Folder" -and $null -eq $ParentFolderDefaults ) {
$ParentFolderDefaults = @{}
if ($null -eq $fieldsToUpdate -or $fieldsToUpdate.Count -gt 0) {
write-Debug "ParentFolderDefaults is null"
$tempfolder=$folder.ParentFolder
while ($tempfolder.ParentListId -ne [Guid]::Empty) {
Write-Debug "at folder $($tempfolder.Url)"
$pairs = $columnDefaults.GetDefaultMetadata($tempfolder)
foreach ($pair in $pairs) {
if (!$ParentFolderDefaults.ContainsKey($pair.First)) {
Write-Debug "Folder $($tempfolder.Name) default: $($pair.First) = $($pair.Second)"
$ParentFolderDefaults.Add($pair.First,$pair.Second)
$tempfolder = $tempfolder.ParentFolder
#listdefaults
Write-Debug "at list"
foreach ($field in $folder.DocumentLibrary.Fields) {
if ($field.InternalName -eq "_ModerationStatus") { continue }
#$field = $list.Fields[$name]
if (![String]::IsNullOrEmpty($field.DefaultValue)) {
#Write-Verbose "List default found key $($field.InternalName)"
if (!$ParentFolderDefaults.ContainsKey($field.InternalName)) {
Write-Debug "List Default $($field.InternalName) = $($field.DefaultValue)"
$ParentFolderDefaults.Add($field.InternalName,$field.DefaultValue)
process {
Write-Debug "Calling with $($PSCmdlet.ParameterSetName)"
Write-Debug "Parent folder hash has $($ParentFolderDefaults.Count) items"
if ($PSCmdlet.ParameterSetName -eq "List" ) {
$folder = $list.RootFolder
$ParentFolderDefaults=@{}
if ($null -eq $fieldsToUpdate -or $fieldsToUpdate.Count -gt 0) {
foreach ($field in $list.Fields) {
if ($field.InternalName -eq "_ModerationStatus") { continue }
if (![String]::IsNullOrEmpty($field.DefaultValue)) {
Write-Debug "List Default $($field.InternalName) = $($field.DefaultValue)"
$ParentFolderDefaults.Add($field.InternalName,$field.DefaultValue)
Write-Verbose "At folder $($folder.Url)"
$FolderDefaults=@{}
$FolderDefaults += $ParentFolderDefaults
if ($null -eq $fieldsToUpdate -or $fieldsToUpdate.Count -gt 0) {
$pairs = $columnDefaults.GetDefaultMetadata($folder)
foreach ($pair in $pairs) {
if ($FolderDefaults.ContainsKey($pair.First)) {
$FolderDefaults.Remove($pair.First)
Write-Debug "Folder $($folder.Name) default: $($pair.First) = $($pair.Second)"
$FolderDefaults.Add($pair.First,$pair.Second)
#set values
foreach ($file in $folder.Files) {
if ($file.CheckOutType -ne [Microsoft.SharePoint.SPFile+SPCheckOutType]::None) {
Write-Warning "File $($file.Url).CheckOutType = $($file.CheckOutType)) ... skipping"
continue
$item = $file.Item
$ItemDefaults=@{}
$ItemDefaults+= $FolderDefaults
#if we only want certain fields then remove the others
#Move this to every time we add values to the defaults
if ($null -ne $fieldsToUpdate ) {
$ItemDefaults2=@{}
foreach ($fieldInternalName in $fieldsToUpdate) {
try {
$ItemDefaults2.Add($fieldInternalName,$ItemDefaults[$fieldInternalName])
} catch { } #who cares if not in list
$ItemDefaults = $ItemDefaults2
#do not overwrite already filled in values unless specified
if (!$overwrite) {
$keys = $itemDefaults.Keys
for ($i=$keys.Count - 1; $i -ge 0; $i-- ) {
$key=$keys[$i]
try {
$val =$item[$item.Fields.GetFieldByInternalName($key)]
if ($val -ne $null) {
$ItemDefaults.Remove($key)
} catch {} #if fieldname does not exist then ignore, we should check for this earlier
#do not overwrite FROM fields in copy list unless specified
if (!$overwriteFromFields) {
if ($null -ne $fieldToCopy -and $fieldsToCopy.Count -gt 0) {
foreach ($value in $fieldsToCopy.Values) {
try {
$ItemDefaults.Remove($value)
} catch {} #who cares if not in list
#do not overwrite TO fields in copy list if we're going to copy instead
if (!$overwriteFromFields) {
if ($null -ne $fieldToCopy -and $fieldsToCopy.Count -gt 0) {
foreach ($key in $fieldsToCopy.Keys) {
$fromfield = $item.Fields.GetFieldByInternalName($fieldsToCopy[$key])
try {
if ($null -ne $item[$fromfield]) {
$ItemDefaults.Remove($key)
} catch {} #who cares if not in list
Write-Verbose $item.Url
$namestr = [String]::Empty
if ($ItemDefaults.Count -eq 0) {
write-Verbose "No defaults, copy only"
} else {
$str = $ItemDefaults | Out-String
$namestr += $str
Write-Verbose $str
if ($null -ne $fieldsToCopy -and $fieldsToCopy.Count -gt 0) {
$str = $fieldsToCopy | Out-String
$namestr +=$str
if ($PSCmdlet.ShouldProcess($item.Url,"Set Values: $namestr"))
#defaults
if ($null -ne $ItemDefaults -and $ItemDefaults.Count -gt 0) {
foreach ($key in $ItemDefaults.Keys) {
$tofield = $item.Fields.GetFieldByInternalName($key)
if ($tofield.TypeAsString -like "TaxonomyFieldType*") {
$taxfield =[Microsoft.SharePoint.Taxonomy.TaxonomyField]$tofield
$taxfieldValue = New-Object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue($tofield)
$lookupval=$ItemDefaults[$key]
$termval=$lookupval.Substring( $lookupval.IndexOf('#')+1)
$taxfieldValue.PopulateFromLabelGuidPair($termval)
if ($tofield.TypeAsString -eq "TaxonomyFieldType") {
$taxfield.SetFieldValue($item,$taxfieldValue)
} else {
#multi
$taxfieldValues = New-Object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValueCollection $tofield
$taxfieldValues.Add($taxfieldValue)
$taxfield.SetFieldValue($item,$taxfieldValues)
} else {
$item[$field]=$ItemDefaults[$key]
#copyfields
if ($null -ne $fieldsToCopy -and $fieldsToCopy.Count -gt 0) {
#$fieldsToCopy | Out-String | Write-Verbose
foreach ($key in $fieldsToCopy.Keys) {
$tofield = $item.Fields.GetFieldByInternalName($key)
$fromfield = $item.Fields.GetFieldByInternalName($fieldsToCopy[$key])
if ($null -eq $item[$fromfield] -or ( !$overwrite -and $null -ne $item[$tofield] )) {
continue
if ($tofield.TypeAsString -eq "TaxonomyFieldType" -and
$fromfield.TypeAsString -notlike "TaxonomyFieldType*" ) {
#non taxonomy to taxonomy
$taxfield =[Microsoft.SharePoint.Taxonomy.TaxonomyField]$tofield
$termSet = $termStore.GetTermSet($taxfield.TermSetId)
[String]$fromval = $item[$fromfield]
$vals = $fromval -split ';#' | where {![String]::IsNullOrEmpty($_)}
if ($null -ne $vals -and $vals.Count -ge 0 ) {
$val = $vals[0]
if ($vals.Count -gt 1) {
write-Warning "$($item.Url) Found more than one value in $($fromfield.InternalName)"
continue
$terms =$termSet.GetTerms($val,$true)
if ($null -ne $terms -and $terms.Count -gt 0) {
$term = $terms[0]
$taxfield.SetFieldValue($item,$term)
Write-Verbose "$($tofield.InternalName) = $($term.Name)"
} else {
Write-Warning "Could not determine term for $($fromfield.InternalName) for $($item.Url)"
continue
} elseif ($tofield.TypeAsString -eq "TaxonomyFieldTypeMulti" -and
$fromfield.TypeAsString -notlike "TaxonomyFieldType*" ) {
Write-Debug "we are here: $($item.Name): $($fromfield.TypeAsString) to $($tofield.TypeAsString )"
#non taxonomy to taxonomy
$taxfield =[Microsoft.SharePoint.Taxonomy.TaxonomyField]$tofield
$termSet = $termStore.GetTermSet($taxfield.TermSetId)
$taxfieldValues = New-Object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValueCollection $tofield
[String]$fromval = $item[$fromfield]
$vals = $fromval -split ';#' | where {![String]::IsNullOrEmpty($_)}
foreach ($val in $vals){
$terms =$termSet.GetTerms($val,$true)
if ($null -ne $terms -and $terms.Count -gt 0) {
$term=$terms[0]
$taxfieldValue = New-Object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue($tofield)
$taxfieldValue.TermGuid = $term.Id.ToString()
$taxfieldValue.Label = $term.Name
$taxfieldValues.Add($taxfieldValue)
} else {
Write-Warning "Could not determine term for $($fromfield.InternalName) for $($item.Url)"
continue
#,[Microsoft.SharePoint.Taxonomy.StringMatchOption]::ExactMatch,
$taxfield.SetFieldValue($item,$taxfieldValues)
$valsAsString = $taxfieldValues | Out-String
Write-Debug "$($tofield.InternalName) = $valsAsString"
} elseif ($tofield.TypeAsString -eq "TaxonomyFieldTypeMulti" -and
$fromfield.TypeAsString -eq "TaxonomyFieldType" ) {
#single taxonomy to multi
$taxfieldValues = New-Object Microsoft.SharePoint.Taxonomy.TaxonomyFieldValueCollection $tofield
$taxfield =[Microsoft.SharePoint.Taxonomy.TaxonomyField]$tofield
$taxfieldValues.Add($item[$fromfield])
$taxfield.SetFieldValue($item,$taxFieldValues)
Write-Verbose "$($tofield.InternalName) = $valsAsString"
} elseif ($tofield.TypeAsString -eq "TaxonomyFieldType" -and
$fromfield.TypeAsString -eq "TaxonomyFieldTypeMulti" ) {
#multi taxonomy to single taxonomy
Write-Warning "multi to non multi - what to do here"
continue
} elseif ($tofield.TypeAsString -eq "Lookup" -and
$fromfield.TypeAsString -ne "Lookup" ) {
#non lookup to lookup
Write-Warning "non lookup to lookup - still todo"
continue
} else {
#straight copy
$item[$tofield] = $item[$fromfield]
$item.SystemUpdate($false)
$folders = $folder.SubFolders | where name -ne "Forms"
$folders | Set-SPListItemValuesToDefaults -ParentFolderDefaults $FolderDefaults -fieldsToCopy $fieldsToCopy -fieldsToUpdate $fieldsToUpdate -overwrite:$overwrite -overwriteFromFields:$overwriteFromFields -termStore $termStore
Maybe you are looking for
-
Opening pdf in IE8 Causes freeze
I'm not sure whats happened but using Adobe Reader 9.3 on my Win7 x64 desktop or my Laptop if I try to open a pdf in the browser it loads up and starts to display but then freezes IE 8.0. It's hit or miss and if I try several times it will sometimes
-
Styles looking different in RH8 for Word source and Webhelp
Hi All, I am using RH8 for Word. There are close to 900 topics in my project. My problem is that the styles that I used in my RH Word documents and the styles displayed after generating Webhlep are looking different. Also, that is not consistent with
-
Lion OS 10.7 and Quicken 2007 - Investments
Ashland A In your transition to SEE you do not mention transfering a history of investments. This is an area where many of us have been left out. Did you transfer a long history (10 years +) of accounts with activity to SEE?
-
Can we set up an Admin for each workflow to handle the errored witems ?
Hi, As this is a Production Issue, i'd really appreciate your immediate response. Is there a way we can specify a user/position/org. unit to get notified automatically whenever some error occurs during runtime, anywhere in the main workflow. That is
-
Hi all, Could you please let me know if the standard purchasing datasources cantain purchase rebate information ? thanks