SharePoint Office365 Powershell Webpart AllItems.aspx - powershell

Using powershell, add webpart (image) to the list view page, e.g. AllItems.aspx.
This code is ok when I adding webpart to sitepage but what/how can do the same things in list
$mySite = Get-PnPClientSidePage -Identity "TestWP.aspx"
$jsonProp = '{
"imageSourceType":0,
"imageSource":"https://MMMMMM.sharepoint.com/sites/pwa/SiteAssets/img01.jpg",
"captionText":" ",
"altText":" ",
"linkUrl":"",
"overlayText":"",
"fileName":"",
"siteId":"",
"webId":"",
"listId":"",
"uniqueId":"",
"imgWidth":"100%",
"imgHeight":"100%"
}'
Add-PnPClientSideWebPart -Page $mySite -Section 1 -Column 1 -Order 1 -DefaultWebPartType Image -WebPartProperties $jsonProp

E.g. in the AllItems.aspx view -> edit page -> Insert -> Image
or Add a Web Part.
example in the link.
img01
img02

coffee, a little break and I got it
first manually adding a web part to the test page then download webpart in xml format
# get xml
$imgWebPart = Get-PnPWebPartXml -ServerRelativePageUrl "/sites/pwa/Lists/TestList03/AllItems.aspx" -Identity "Image Viewer"
Add-PnPWebPartToWebPartPage -ServerRelativePageUrl "/sites/pwa/Lists/TestList03/aa.aspx" -Xml $imgWebPart -ZoneId Main -ZoneIndex 0
sorry for the confusion.

Related

Error when updating link urls in quick launch on sharepoint 2013 site with powershell

I have a problem when trying to update link urls in quick launch on sharepoint 2013 site with powershell. Basically I only want to change the url of specific links. My Powershell script code is as follows:
function FixUrlDocumentsLists() {
param([Microsoft.SharePoint.SPWeb]$SiteIdentity)
if ($SiteIdentity.Url -Like "http://mktintranet/sites/tmmkto/ITReports")
{
$quicklaunch = $SiteIdentity.Navigation.QuickLaunch
if($quicklaunch.Count -gt 0)
{
foreach($node in $quicklaunch)
{
if ($node.Title.ToUpper() -ne "HOME" -and $node.Title.ToUpper() -ne "SITE CONTENTS")
{
if($node.Url -eq $SiteIdentity.ServerRelativeUrl)
{
Write-Host "Fixing navigation links for web $($SiteIdentity.Title)" -ForegroundColor Yellow
Write-Host "Link Title: $($node.Title), OLD Link Url: $($node.Url)" -ForegroundColor Yellow
$node.Url=$node.Url.ToString()+"/_layouts/15/viewlsts.aspx"
Write-Host "Link Title: $($node.Title), NEW Link Url: $($node.Url)" -ForegroundColor Yellow
$node.Update()
$SiteIdentity.Update()
}
}
}
}
}
if($SiteIdentity.Webs.Count -gt 0)
{
foreach($subWeb in $SiteIdentity.Webs)
{
FixUrlDocumentsLists -SiteIdentity $subWeb
}
}
}
The error occurs on $node.Update() method. The error description is as follows:
Exception calling "Update" with "0" argument(s): "Cannot open "/sites/tmmkto/ITReports/_layouts/15/viewlsts.aspx": no such file or folder."
I can't realize why the Update method is making Url validation. Even though the path /sites/tmmkto/ITReports/_layouts/15/viewlsts.aspx does exists.
Thanks,
Martin
SharePoint try and verify the node url if it is an internal url. On way around this is to mark your link as external (even though it is not) by:
Node.IsExternal = true; (csom)
Please ensure Show sub sites/Show pages option is unchecked under
Site Settings =>Navigation => Current Navigation=>
in Navigation: Display only the navigation items below the current site. You will get such error, if you try to update the Navigation links generating from the Sub Site/ Page files. It make sense for giving error if this option in on and you try to modify the link for auto generated sub site/Page link.

How to add a text file or xml content to a TFS WorkItem description in Powershell?

I want to add some description in a TFS Workitem using powershell.
I wrote following code:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.WorkItemTracking.Client")
# Get TFS server and query from WIQ file
[xml]$WiqlXML = Get-Content $WiqPath
[String]$TFSservername = $WiqlXML | % {$_.WorkItemQuery.TeamFoundationServer}
[String]$queryString = $WiqlXML | % {$_.WorkItemQuery.Wiql}
$teamProjectCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($TFSservername)
# Get workitem collection from TFS Project
$ws = $teamProjectCollection.GetService([type][Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore])
$wis = $ws.Query($queryString);
[Net.WebClient] $request = New-Object Net.WebClient
$request.UseDefaultCredentials = $true
foreach($wi in $wis)
{
$wi.Description += "`r`n========================================================"
$wi.Description += "<xml>content</xml>"
}
But, in the workitem only ======================================================== is added
All of your content is added, however as it is an HTML box it is not rendered and disappears.
You need to HTML encode your xml before adding it to the description field.

How do I retrieve PR_RULE_ACTIONS via PowerShell and the EWS Managed API?

I have need of retrieving and inspecting the delegate forwarding rule (the built-in delegate commands in EWS being inadequate for my needs since they choke on groups being used as delegates).
I am able to successfully locate the rule created by "Schedule+ EMS Interface". However, I am unable to retrieve PR_RULE_ACTIONS. Turning on tracing.
I see that the PidTagRuleMsgProvider property is getting returned just fine, but PR_RULE_ACTIONS never does.
I suspect that I am using the wrong MAPI property type in the propertyset definition, but I've gone through everything listed at http://msdn.microsoft.com/en-us/library/exchangewebservices.mapipropertytypetype(v=exchg.140).aspx . Any clues?
Here is the relevant snippet of code:
# Setup Basic EWS Properties for Message Search - Used to locate Hidden Forwarding Rule
$searchFilterForwardRule = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Rule", [Microsoft.Exchange.WebServices.Data.ContainmentMode]::Prefixed, [Microsoft.Exchange.WebServices.Data.ComparisonMode]::Exact)
$itemViewForwardRule = New-Object Microsoft.Exchange.WebServices.Data.ItemView(30, 0, [Microsoft.Exchange.Webservices.Data.OffsetBasePoint]::Beginning)
$itemViewForwardRule.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties, [Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, [Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)
$itemViewForwardRule.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated
# Properties for Hidden Delegate Forwarding Rule
$PID_TAG_RULE_MSG_PROVIDER = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x65EB,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String)
$PID_TAG_RULE_ACTIONS = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6680,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)
# Property Set for Delegate Forward Rule
$propertySetForwardRule = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties, $PID_TAG_RULE_MSG_PROVIDER)
$forwardRuleExists = $false
$findResults = $service.FindItems([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $searchFilterForwardRule, $itemViewForwardRule)
If ($findResults.TotalCount -lt 1) {
Write-Error "Failed to find rule" "Error"
} Else {
Foreach ($item in $findResults.Items) {
$item.Load($propertySetForwardRule)
If ($item.ExtendedProperties.Count -ge 1) {
If ($item.ExtendedProperties[0].Value -eq "Schedule+ EMS Interface") {
$forwardRuleExists = $true
write-host "Delegate forwarding rule found." -ForegroundColor Cyan
$propertySetForwardRule.Add($PID_TAG_RULE_ACTIONS)
$item.Load($propertySetForwardRule)
Write-Host "Attempting to retrieve x6680 PR_RULE_ACTIONS (PidTagRuleActions)" -ForegroundColor Cyan
$PR_RULE_ACTIONS = $null
if($Item.TryGetProperty($Pid_Tag_Rule_Actions,[ref]$PR_RULE_ACTIONS)){
return $PR_RULE_ACTIONS
} # endif
else {write-host "TryGetProperty for PR_RULE_ACTIONS failed!" -ForegroundColor Red
} # endelse
} # End If - Correct Message
} # End If - Has Extended Properties
} # End ForEach
} # End If - Message Count
Glen Scales was able to set me on the right path. It turns out that PR_RULE_ACTIONS is not exposed via EWS, but the same data exposed via an attribute called PR_EXTENDED_RULE_ACTIONS. Now I'm happily slinging code to parse the binary blob.
http://msdn.microsoft.com/en-us/library/ee218391(v=EXCHG.80).aspx
The property tag for PR_RULE_ACTIONS is 0x668000FE. You can see it (and the property data) in OutlookSpy (I am its author) - go to the Inbox folder, click IMAPIFolder button, go to the PR_RULES_TABLE tab, select the rule, double click on the PR_RULE_ACTIONS property.
Note that PT_ACTIONS MAPI type (0x000FE) is only accessing in Extended MAPI, I don't think EWS will be able to return it.

Add Wiki Page Library pages (not the publishing wiki) with PowerShell CSOM SharePoint 2013

Made a Wiki Page Library (not the publishing wiki) and can add pages with content like below, but when the page renders there is no SharePoint Chrome, just my content shows up. here is code. I it seems there may be one more property to add so master page takes effect?
$FileCreationInformation = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInformation.Url = $FileRef
$FileCreationInformation.Overwrite = $true
$FileCreationInformation.Content = [System.Text.Encoding]::UTF8.GetBytes($HTMLPageContent)
$wikiFile = $WikiPageList.RootFolder.Files.Add($FileCreationInformation)
$ClientContext.Load($wikiFile)
$ClientContext.ExecuteQuery()
How to create a page in Wiki Page Library using CSOM in SharePoint 2013
Use Utility.CreateWikiPageInContextWeb method to create a page in Wiki Page Library:
Function Create-WikiPage([Microsoft.SharePoint.Client.ClientContext]$Context,[string]$WikiLibraryTitle,[string]$PageName,[string]$PageContent)
{
$wikiLibrary = $Context.Web.Lists.GetByTitle($wikiLibraryTitle)
$Context.Load($wikiLibrary.RootFolder)
$Context.ExecuteQuery()
$wikiPageInfo = New-Object Microsoft.SharePoint.Client.Utilities.WikiPageCreationInformation
$wikiPageInfo.WikiHtmlContent = $PageContent
$wikiPageInfo.ServerRelativeUrl = [String]::Format("{0}/{1}", $wikiLibrary.RootFolder.ServerRelativeUrl, $PageName)
$wikiFile = [Microsoft.SharePoint.Client.Utilities.Utility]::CreateWikiPageInContextWeb($Context, $wikiPageInfo)
$context.ExecuteQuery()
}
Usage
$context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
Create-WikiPage -Context $Context -WikiLibraryTitle "KBList" -PageName "Welcome.aspx" -PageContent "Welcome to the SharePoint!"
$context.Dispose()

Get Tfs Shelveset file contents at the command prompt?

I'm interested in getting the contents of a shelveset at the command prompt. Now, you would think that a cmdlet such as Get-TfsShelveset, available in the TFS Power Tools, would do this. You might also think that "tf.exe shelvesets" would do this.
However, unless I've missed something, I'm appalled to report that neither of these is the case. Instead, each command requires you to give it a shelveset name, and then simply regurgitates a single line item for that shelveset, along with some metadata about the shelveset such as creationdate, displayname, etc. But as far as I can tell, no way to tell what's actually in the shelf.
This is especially heinous for Get-TfsShelveset, which has the ability to include an array of file descriptors along with the Shelveset object it returns. I even tried to get clever, thinking that I could harvest the file names from using -WhatIf with Restore-TfsShelveset, but sadly Restore-TfsShelveset doesn't implement -WhatIf.
Please, someone tell me I'm wrong about this!
tf status /shelveset:name
will list out the content of the named shelveset (you can also supplier an owner: see tf help status).
With the TFS PowerToy's PowerShell snapin:
Get-TfsPendingChange -Shelveset name
for the same information.
It is possible to construct a small command-line application that uses the TFS SDK, which returns the list of files contained in a given shelveset.
The sample below assumes knowledge of the Shelveset name & it's owner:
using System;
using System.IO;
using System.Collections.ObjectModel;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace ShelvesetDetails
{
class Program
{
static void Main(string[] args)
{
Uri tfsUri = (args.Length < 1) ? new Uri("TFS_URI") : new Uri(args[0]);
TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
ReadOnlyCollection<CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren(
new[] { CatalogResourceTypes.ProjectCollection },
false, CatalogQueryOptions.None);
CatalogNode collectionNode = collectionNodes[0];
Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
var vcServer = teamProjectCollection.GetService<VersionControlServer>();
Shelveset[] shelves = vcServer.QueryShelvesets(
"SHELVESET_NAME", "SHELVESET_OWNER");
Shelveset shelveset = shelves[0];
PendingSet[] sets = vcServer.QueryShelvedChanges(shelveset);
foreach (PendingSet set in sets)
{
PendingChange[] changes = set.PendingChanges;
foreach (PendingChange change in changes)
{
Console.WriteLine(change.FileName);
}
}
}
}
}
Invoking this console app & catching the outcome during execution of the powershell should be possible.
Try:
tfpt review
/shelveset:shelvesetName;userName
You may also need to add on the server option so something like:
tfpt review /shelveset:Code Review;jim
/sever:company-source
I think this is what you are looking for.
This is what I ended up with, based on pentelif's code and the technique in the article at http://akutz.wordpress.com/2010/11/03/get-msi/ linked in my comment.
function Get-TfsShelvesetItems
{
[CmdletBinding()]
param
(
[string] $ShelvesetName = $(throw "-ShelvesetName must be specified."),
[string] $ShelvesetOwner = "$env:USERDOMAIN\$env:USERNAME",
[string] $ServerUri = $(throw "-ServerUri must be specified."),
[string] $Collection = $(throw "-Collection must be specified.")
)
$getShelvesetItemsClassDefinition = #'
public IEnumerable<PendingChange> GetShelvesetItems(string shelvesetName, string shelvesetOwner, string tfsUriString, string tfsCollectionName)
{
Uri tfsUri = new Uri(tfsUriString);
TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
ReadOnlyCollection<CatalogNode> collectionNodes = configurationServer.CatalogNode.QueryChildren( new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None);
CatalogNode collectionNode = collectionNodes.Where(node => node.Resource.DisplayName == tfsCollectionName).SingleOrDefault();
Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
var vcServer = teamProjectCollection.GetService<VersionControlServer>();
var changes = new List<PendingChange>();
foreach (Shelveset shelveset in vcServer.QueryShelvesets(shelvesetName, shelvesetOwner))
{
foreach (PendingSet set in vcServer.QueryShelvedChanges(shelveset))
{
foreach ( PendingChange change in set.PendingChanges )
{
changes.Add(change);
}
}
}
return changes.Count == 0 ? null : changes;
}
'#;
$getShelvesetItemsType = Add-Type `
-MemberDefinition $getShelvesetItemsClassDefinition `
-Name "ShelvesetItemsAPI" `
-Namespace "PowerShellTfs" `
-Language CSharpVersion3 `
-UsingNamespace System.IO, `
System.Linq, `
System.Collections.ObjectModel, `
System.Collections.Generic, `
Microsoft.TeamFoundation.Client, `
Microsoft.TeamFoundation.Framework.Client, `
Microsoft.TeamFoundation.Framework.Common, `
Microsoft.TeamFoundation.VersionControl.Client `
-ReferencedAssemblies "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.Client.dll", `
"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.Common.dll", `
"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0\Microsoft.TeamFoundation.VersionControl.Client.dll" `
-PassThru;
# Initialize an instance of the class.
$getShelvesetItems = New-Object -TypeName "PowerShellTfs.ShelvesetItemsAPI";
# Emit the pending changes to the pipeline.
$getShelvesetItems.GetShelvesetItems($ShelvesetName, $ShelvesetOwner, $ServerUri, $Collection);
}
Spent a few days trying to do this as well, this always popped up on google so here is what I found to help future generations:
To get the contents of the shelveset (at least with Team Explorer Everywhere),
use the command: tf difference /shelveset:<Shelveset name>
That will print out the contents of the shelveset and give filenames in the form :
<Changetype>: <server file path>; C<base change number>
Shelved Change: <server file path again>;<shelveset name>
So if your file is contents/test.txt
in the shelveset shelve1 (with base revision 1), you will see :
edit: $/contents/file.txt;C1
Shelved Change: $/contents/file.txt;shelve1
After that, using the tf print command
(or view if not using TEE) on $/contents/file.txt;shelve1 should get you the contents :
tf print $/contents/file.txt;shelve1
Shows you what is in the file.txt in shelveset shelve1
If you want get shelveset changes from server by using tfs command
Using power shell:
Get-TfsPendingChange -Server http://example.com/org -Shelveset shelvsetName
Using vs commands:
c:\projects>tf shelvesets BuddyTest_23
more info about this please see here
https://learn.microsoft.com/en-us/azure/devops/repos/tfvc/shelvesets-command?view=azure-devops