Sharepoint
PowerApps Functions
By fredericdietrich On 30/09/2022
PowerApps functions
Parse text to number
Filter('Workflow Tasks'; ID = Value(txtId.Text))
Add datas (listItem)
Patch(NewVoie;Defaults(NewVoie);{Num_x00e9_rovoie:"0"&LookUp(NewVoie;ID=1).Num_x00e9_rovoie}))
Update context, and forms datas
SubmitForm(FormBeneficiaires);;ResetForm(FormBeneficiaires);; NewForm(FormBeneficiaires);; UpdateContext({showPopup:false});
Navigate to another form
Navigate(Page_infos_enregistrements)
Get query string parameter and set a variable
Set(InitiativeId; Param("ID"))
Get a field from your datasource by ID
First(Filter(Initiatives; ID=1)).Nom
And Or Not
Or(And(Radio1.Selected.Value=4; !IsBlank(txtComment.Text));Radio1.Selected.Value<4)
Update Lookup Field
Patch(
ResultatAnalyses;
First(//here item to update
Filter(
ResultatAnalyses;
Affaire.Id = currentAffaire.ID And Analyse.Id = ThisItem.ID
)
);
{
Title: "notused";
Commentaires: txtGalComment.Text;
Gravite: Rating1.Value;
Affaire: {//lookup field name
Id: currentAffaire.ID;//id of lookup
Value: LookUp(
Affaires;//list who contains lookup value
ID = currentAffaire.ID;//id of lookup
currentAffaire.Title//title of lookup value
)
}
}
)
Patch Choice
TypeIntervention: {Value: dtvTypeIntervention.Selected.Value}
Execute automate with json
'My workflow'.Run(
JSON(
{
SolutionId: selectedSolution.ID,
ImageContent: UploadedImage14.Image
},
JSONFormat.IncludeBinaryData
)
);
Reg ex to get cleaned string
Clear(AttachmentsCollection);
ForAll(
RenameColumns(DataCardValue91.Attachments, "Name", "Name1"),
Collect(
AttachmentsCollection,
Name1
)
);Set(Title1, First(AttachmentsCollection).Value);Set(FileName1, Concat( Split(First(AttachmentsCollection).Value, "" ), If( IsMatch(Result, "([^A-Za-z0-9\.\-])" ), "",Result ) ))
Save Form
SubmitForm(Form1);;If(!IsBlankOrError( Form1.Error); Notify("Une erreur est survenue lors de la sauvegarde " & Form1.Error; NotificationType.Error);Notify("La savegarde a réussi";NotificationType.Information);;Set(currentElement; Form1.LastSubmit))
Sort columns
Set(Month, Distinct(SortByColumns(CurrentMonthMails, "Year", Ascending, "Month", Ascending), Month))
Set date
Set(StartDate, DateAdd(DateTimeValue( Day(Today) &"/"& Month(Today) &"/"& Year(Today) &" 00:00:00"), -30));
Sum
Sum(Filter(CurrentMonthMails, Month = ThisItem.Result ), uniqMails)
Sharepoint REST
By fredericdietrich On 19/02/2024
PnP references
Get field in list
/_api/Web/Lists/getbytitle('Pages')/Fields?$select=InternalName,Id,Hidden,TypeAsString,Required&$filter=InternalName eq 'Title'
Get list content types
Get contentType fields
/_api/Web/Lists/getbytitle('Pages')/ContentTypes('0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF390028D78BF8D3054E38BEF0590B43C4BA0E00572E4F21E9A2274ABC0C3A6B4238D562')/fields?$filter=(Hidden eq false)and (Group ne '_Hidden')&$select= InternalName,Hidden,Required,Title,TypeAsString,Required,Id,Group
Query search
/_api/search/query?querytext='Path:https://mcn365.sharepoint.com/sites/a_IntranetPays_42/sitePages/*'&selectproperties='Title,Path'
/_api/search/query?querytext='owstaxIdJiveTags:GP0*+OR+owstaxIdJiveCategories:GP0*'&rowsperpage=0&rowlimit=5&selectproperties='Title%2cowstaxIdJiveCategories%2cowstaxIdJiveTags'&sortlist='Rank:descending%2cmodifiedby:ascending'&clienttype='ContentSearchRegular'">https://mcncs36sddcsdcsint.com/sites/a_IntranetPays_42/_api/search/query?querytext='owstaxIdJiveTags:GP0*+OR+owstaxIdJiveCategories:GP0*'&rowsperpage=0&rowlimit=5&selectproperties='Title%2cowstaxIdJiveCategories%2cowstaxIdJiveTags'&sortlist='Rank:descending%2cmodifiedby:ascending'&clienttype='ContentSearchRegular'
/_api/Web/Lists/getbytitle('Pages')/ContentTypes('0x010100C568DB52D9D0A1d37AF390028D78BF8D3054E38BEF0590B43C4BA0E00572E4F21E9A2274ABC0C3A6B4238D562')/fields?$filter=(Hidden eq false)and (Group ne '_Hidden')&$select= InternalName,Hidden,Required,Title,TypeAsString,Required,Id,Group
query user multi
/_api/web/lists/getbytitle('ResponsableRegions')/items(1)?$select=ResponsablesRegions/EMail,Id&$expand=ResponsablesRegions
get fields
/_api/web/lists/GetByTitle('Liste des chantiers')/fields?$filter=Hidden eq false&$orderby=Title&$select=Title,InternalName,TypeAsString,Hidden
Power Automate We are unable to find the site address. Please try selecting a site address from the dropdown.
By fredericdietrich On 24/10/2023
Power Automate, cannot access to my site
We are unable to find the site address. Please try selecting a site address from the dropdown.
If you don't found your site in dropDown list or your site cannot be used
you can add you url manually in custom value, then you cannot select a list, but you can set id id of the list and it will work
get the id in your list when you navigate in your list setting
SKIP %7B and %7D
Save and it should be ok
The list ID should be replaced by the correct list title
Prevent Recursive Update
By fredericdietrich On 24/10/2023
How to prevent recursives update on trigger "When an item is created or modified"
add this in trigger settings, set your email (a service account) thaht will not launch the trigger
@not(equals(toLower(triggerOutputs()?['body/Author/Email']), 'service_account@test1.com'))
so with this settings you can perform an update in your flow without recursive trigger
Csom Context Sharepoint ClientContext
By fredericdietrich On 23/05/2023
c# Connect to Sharepoint with ClientContext appId and certificat ThumbPrint
using Microsoft.Identity.Client;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace MY.PNP.Powershell.EXT.CSOM
{
public class CsomContext : IDisposable
{
public ClientContext _clientContext;
public ClientRuntimeContext _context;
private async Task GetAccessToken(string tenantName, string clientId, string thumbprint)
{
var certificate = GetCert(thumbprint);
var authority = $"https://login.microsoftonline.com/{tenantName}.onmicrosoft.com/";
var azureApp = ConfidentialClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.WithCertificate(certificate)
.Build();
var scopes = new string[] { $"https://{tenantName}.sharepoint.com/.default" };
var authResult = await azureApp.AcquireTokenForClient(scopes).ExecuteAsync();
return authResult.AccessToken;
}
public async Task CallClientObjectModel(string tenantName, string url, string clientId, string thumbprint)
{
var token = await GetAccessToken(tenantName, clientId, thumbprint);
var siteUrl = url;//;$"https://{tenantName}.sharepoint.com";
var context = new ClientContext(siteUrl);
context.ExecutingWebRequest += (s, e) =>
{
e.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + token;
};
var web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine(web.Title);
Console.WriteLine(web.Url);
_context = web.Context;
_clientContext = context;
}
private X509Certificate2 GetCert(string thumbprint)
{
X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = certStore.Certificates.Find(
X509FindType.FindByThumbprint,
// Replace below with your cert's thumbprint
thumbprint,
false);
X509Certificate2 cert = null;
// Get the first cert with the thumbprint
if (certCollection.Count > 0)
{
cert = certCollection[0];
// Use certificate
Console.WriteLine(cert.FriendlyName);
}
certStore.Close();
return cert;
}
public void Dispose()
{
if (_context != null)
_context.Dispose();
if (_clientContext != null)
_clientContext.Dispose();
}
}
}
JSON Formatting Show File Size
By fredericdietrich On 03/05/2023
Show File size in kilo bytes in sharepoint list
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
"elmType": "div",
"attributes": {
},
"style": {
"flex-directon": "row",
"justify-content": "left",
"align-items": "center",
"flex-wrap": "nowrap"
},
"children": [
{
"elmType": "span",
"txtContent": "=[$File_x0020_Size]/1000 + ' kbytes'"
}
]
}
JSON Formatting Is Member of Group
By fredericdietrich On 11/04/2023
show button if user if member of a sharepoint group
Compaire now + 30 days
@now>[$testDate]+2592000000
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
"elmType": "div",
"style": {
"flex-directon": "row",
"justify-content": "left",
"align-items": "center",
"flex-wrap": "nowrap"
},
"children": [
{
"elmType": "div",
"style": {
"display": "=if(([$ItemStatus] == 'Pending' || [$ItemStatus] == '') && ([$PermMask]=='0x1b03c5b1bff' || [$PermMask]=='0x7ffffffffffbffff'), 'inherit','none')",
"flex-directon": "row",
"justify-content": "left",
"align-items": "center",
"flex-wrap": "wrap"
},
"children": [
{
"elmType": "button",
"customRowAction": {
"action": "setValue",
"actionInput": {
"ItemStatus": "Approved",
"ApprovalActionBy": "@me"
}
},
"attributes": {
"class": "ms-fontColor-themePrimary ms-fontColor-themeDarker--hover"
},
"style": {
"border": "none",
"display": "=if([$PermMask]>='0x1b03c5b1bff', 'inherit','none')",
"background-color": "transparent",
"cursor": "pointer",
"display": "flex",
"flex-directon": "row",
"justify-content": "left",
"align-items": "center",
"flex-wrap": "wrap"
},
"children": [
{
"elmType": "span",
"attributes": {
"iconName": "SkypeCircleCheck"
},
"style": {
"padding": "4px"
}
},
{
"elmType": "span",
"txtContent": "Approve",
"style": {
"word-break": "keep-all"
}
}
]
},
{
"elmType": "button",
"customRowAction": {
"action": "setValue",
"actionInput": {
"ItemStatus": "Rejected",
"ApprovalActionBy": "@me"
}
},
"attributes": {
"class": "ms-fontColor-themePrimary ms-fontColor-themeDarker--hover"
},
"style": {
"border": "none",
"display": "=if(([$ItemStatus] == 'Pending' || [$ItemStatus] == ''), 'inherit','none')",
"background-color": "transparent",
"cursor": "pointer",
"display": "flex",
"flex-directon": "row",
"justify-content": "left",
"align-items": "center",
"flex-wrap": "wrap"
},
"children": [
{
"elmType": "span",
"attributes": {
"iconName": "Blocked"
},
"style": {
"padding": "4px"
}
},
{
"elmType": "span",
"txtContent": "Reject",
"style": {
"word-break": "keep-all"
}
}
]
}
]
},
{
"elmType": "div",
"children": [
{
"elmType": "span",
"txtContent": "='This item is ' + toLowerCase([$ItemStatus])",
"style": {
"display": "=if([$ItemStatus] == 'Pending' ||[$ItemStatus] == '' , 'none','inherit')",
"padding-left": "5px",
"word-break": "keep-all"
}
}
]
}
]
}
PowerShell List Big Files
By fredericdietrich On 07/04/2023
Get Sharepoint all Big files with powershell and Sharepoint Search
Import-Module PnP.PowerShell
# Connect-PnPOnline -Url $url -UseWebLogin
$select = "Title,SiteTitle,SPSiteURL,SPWebUrl,ViewsLifeTimeUniqueUsers,ViewsLifeTime,language,Created,Size,Path,LastModifiedTime,ViewsLastMonths3,ViewsLastMonths3Unique,LastAnalyticsUpdateTime,ViewerCount"
$sortlist = @{Size = 'descending' }
$siteName = "serviceanimationreseauFPFSITW"
$search = Submit-PnPSearchQuery -Query "ContentTypeId:0x0101*" -MaxResults 500 -SelectProperties $select -TrimDuplicates $true -SortList $sortlist -StartRow 0
$ret = $search.ResultRows.Count
$count = 0
$stop = $false
$itemsToSave = @();
while ($ret -eq 500 -and -not $stop) {
# Disconnect-PnPOnline
# -MaxResults 10
$lastSize = 0
foreach ($row in $search.ResultRows) {
$mo = 0;
[Int64]::TryParse($row["Size"], [ref] $mo ) | Out-Null
$nice = '{0:N0}' -f $mo
$data = [PSCustomObject]@{
"Title" = $row["Title"]
"Size" = $row["Size"]
"SizeMo" = '{0:N0}' -f ($mo / 1000000)
"NiceSize" = $nice
"SiteTitle" = $row["SiteTitle"]
"ViewsLifeTimeUniqueUsers" = $row["ViewsLifeTimeUniqueUsers"]
"ViewsLifeTime" = $row["ViewsLifeTime"]
"language" = $row["language"]
"Created" = $row["Created"]
"LastModifiedTime" = $row["LastModifiedTime"]
"ViewsLastMonths3" = $row["ViewsLastMonths3"]
"ViewsLastMonths3Unique" = $row["ViewsLastMonths3Unique"]
"LastAnalyticsUpdateTime" = $row["LastAnalyticsUpdateTime"]
"ViewerCount" = $row["ViewerCount"]
"Path" = $row["Path"]
"SPSiteURL" = $row["SPSiteURL"]
"SPWebUrl" = $row["SPWebUrl"]
}
$lastSize = $data.Size
if ([int64]::Parse($data.Size) -lt 10000000) {
$stop = $true;
break;
}
$itemsToSave += $data
}
$count += 500
$search = Submit-PnPSearchQuery -Query "ContentTypeId:0x0101*" -MaxResults 500 -SelectProperties $select -TrimDuplicates $true -SortList $sortlist -StartRow $count
$ret = $search.ResultRows.Count
Write-Host "$($itemsToSave.Count) $($count) $($lastSize)"
}
$itemsToSave | Export-Csv -Path "AllSites_8.csv" -Encodin:UTF8 -NoTypeInformation -Delimiter ";"
Disconnect-PnPOnline
Get Sharepoint Audit Logs
By fredericdietrich On 05/04/2023
Create certification for azure app
# Create certificate
$mycert = New-SelfSignedCertificate -DnsName "myCertificate.org" -CertStoreLocation "cert:\CurrentUser\My" -NotAfter (Get-Date).AddYears(1) -KeySpec KeyExchange
$mypwd = ConvertTo-SecureString -String "myCertificatePsw" -Force -AsPlainText
# Export certificate to .pfx file
$mycert | Export-PfxCertificate -FilePath myCertificate.pfx -Password $mypwd
# Export certificate to .cer file
$mycert | Export-Certificate -FilePath myCertificate.cer
Connect to site
$url = "https://m365x6422vvvvd.sharepoint.com/";
$appId = "868d7a0c-a3dc-45af-b4a7-f72a70f61a60";
$thumbprint = "A17177BB0E8A465F6AD08B0CEAE2F369C46D6481";
$tenantId = "3533ab30-c2f0-48fd-b4c5-f5dc6ca77ec3"
Connect-PnPOnline -Url $url -Tenant $tenantId -Thumbprint $thumbprint -ClientId $appId
Export audit
premission required
Office 365 Management APIs (3) :: ActivityFeed.Read
possible filters
- FilePreviewed
- FileAccessed
- SignInEvent
- FileModifiedExtended
- FileUploaded
- PageViewed
- PagePrefetched
- FileCheckedIn
- FileModified
- FolderCreated
- ListUpdated
- ListViewed
$ele = Get-PnPUnifiedAuditLog -ContentType SharePoint -StartTime (Get-Date).AddDays(-2) -EndTime (Get-Date).AddDays(-1)
$ele = Get-PnPUnifiedAuditLog -ContentType SharePoint
$ele = Get-PnPUnifiedAuditLog -ContentType SharePoint | Where-Object {$_.Operation -eq "PageViewed"} | Select-Object CreationTime,Operation,Workload,UserId,ObjectId,SourceFileName,SiteUrl,SourceFileExtension,SourceRelativeUrl
$ele | Export-Csv -Path "Audit_3.csv" -Encodin:UTF8 -NoTypeInformation -Delimiter ";"
with sharepoint search request
kqlQuery = "ContentTypeId:0x0101009D1CB255DA76424F860D91F20E6C4118*";//news
kqlQuery = "ContentTypeId:0x0101* language=fr ViewsLastMonths3=0";//documents
kqlQuery = "ContentTypeId:0x0101* ViewsLifeTime=0";
var seletvvv = "Title,ViewsLifeTimeUniqueUsers,ViewsLifeTime,language,Created,Size,Path,LastModifiedTime,ViewsLastMonths3,ViewsLastMonths3Unique,LastAnalyticsUpdateTime";
&sortlist='Size:descending'
&sortlist='ViewsLifeTime:descending'
Power Automate add line to Excel
By fredericdietrich On 29/03/2023
Copy an Excel file from a template with an Sharepoint Http request
/_api/web/getFileByServerRelativeUrl('/sites/test@{variables('TemplateFileName')}')/copyTo(strNewUrl='/sites/test@{variables('ExportFolder')}/@{variables('ExportFileName')}',bOverWrite=true)
Header
{
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose",
"X-HTTP-Method": "PATCH",
"If-Match": "*"
}
Create An Excel Table
Add your Datas in an Excel line
Line :
@{items('Appliquer_à_chacun_2')}
Connect Sharepoint With AppID Certificate
By fredericdietrich On 21/03/2023
Connect to Sharepoint using app registration and certificate
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Graph;
using PnP.Core.Auth;
using PnP.Core.Auth.Services.Builder.Configuration;
using PnP.Core.Services;
using PnP.Core.Services.Builder.Configuration;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace HGH.Buisiness4
{
public class SPTools2 : IDisposable
{
private IHost _host;
public SPTools2()
{
}
public async Task Connect(string appId, string tenantId, string siteUrl, string thumbprint, StoreName storeName, StoreLocation storeLocation)
{
try
{
_host = Host.CreateDefaultBuilder()
.ConfigureServices((hostingContext, services) =>
{
// Add the PnP Core SDK library
services.AddPnPCore(options =>
{
options.Sites.Add("SiteToWorkWith", new PnPCoreSiteOptions
{
SiteUrl = siteUrl
});
});
services.AddPnPCoreAuthentication(
options =>
{
// Configure an Authentication Provider relying on Windows Credential Manager
options.Credentials.Configurations.Add("x509certificate",
new PnPCoreAuthenticationCredentialConfigurationOptions
{
ClientId = appId,
TenantId = tenantId,
X509Certificate = new PnPCoreAuthenticationX509CertificateOptions
{
StoreName = storeName,
StoreLocation = storeLocation,
Thumbprint = thumbprint
}
});
// Configure the default authentication provider
options.Credentials.DefaultConfiguration = "x509certificate";
// Map the site defined in AddPnPCore with the
// Authentication Provider configured in this action
options.Sites.Add("SiteToWorkWith",
new PnPCoreAuthenticationSiteOptions
{
AuthenticationProviderName = "x509certificate"
});
});
})
// Let the builder know we're running in a console
.UseConsoleLifetime()
// Add services to the container
.Build();
await _host.StartAsync();
}
catch (Exception ex)
{
Console.WriteLine($"ERROR SPTools2 appId {appId} siteUrl {siteUrl} thumbprint {thumbprint} {ex}");
throw new Exception($"ERROR SPTools2 appId {appId} siteUrl {siteUrl} thumbprint {thumbprint}", ex);
}
return 1;
}
public async Task LoadWeb()
{
try
{
// Optionally create a DI scope
using (var scope = _host.Services.CreateScope())
{
// Obtain a PnP Context factory
var pnpContextFactory = scope.ServiceProvider
.GetRequiredService();
// Use the PnP Context factory to get a PnPContext for the given configuration
using (var context = await pnpContextFactory.CreateAsync("SiteToWorkWith"))
{
// Retrieving web with lists and masterpageurl loaded ==> SharePoint REST query
var web = await context.Web.GetAsync(p => p.Title, p => p.Lists,
p => p.MasterUrl);
Console.WriteLine($"Web Title {web.Title} Loaded");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"ERROR LoadWeb{ex}");
throw new Exception($"ERROR LoadWeb ", ex);
}
return 1;
}
public void Dispose()
{
if (_host != null)
_host.Dispose();
}
}
}
PowerAutomate Add Folder
By fredericdietrich On 10/02/2023
Powerautomate get folder by url
/_api/web/GetFolderByServerRelativeUrl('@{variables('WebserverRelativeUrl')}/@{variables('DoclibUrl')}/Fiche_@{variables('FicheId')}')
Verify status (exists = 200, does not exists = 404)
@{outputs('HttpGetFolder')['statusCode']}
Create folder
/_api/web/folders/add('@{variables('DoclibUrl')}/Fiche_@{variables('FicheId')}')
Powershell Import Export Fields
By fredericdietrich On 03/02/2023
Write-Output 'Connexion Portail'
# Connect-PnPOnline -Url $siteUrl -Tenant $aadDomain -Thumbprint $certifThumbprint -ClientId $appId
function ExportFieldsToCsv {
Param(
[string]$listTitle,
[string]$csvFilename,
[boolean]$includeHidden = $false
)
#$list = Get-PnPList -Identity $list
if ([string]::IsNullOrEmpty($listTitle)) {
$fields = Get-PnPField
$aFieldToExports = @();
for ($i = 0 ; $i -lt $fields.Length ; $i++) {
$field = $fields[$i];
$aFieldToExport = New-Object -TypeName PSObject -Property @{
'Title' = $field.Title;
'InternalName' = $field.InternalName;
'Id' = $field.Id;
'TypeAsString' = $field.TypeAsString;
'Hidden' = $field.Hidden;
'StaticName' = $field.StaticName;
'Required' = $field.Required;
'Description' = $field.Description;
'TypeDisplayName' = $field.TypeDisplayName;
'Group' = $field.Group;
}
$aFieldToExports += $aFieldToExport
$aFieldToExports | Export-Csv -Path "$($csvFilename)" -Encodin:UTF8 -NoTypeInformation -Delimiter ";"
}
}
else {
<# Action when all if and elseif conditions are false #>
}
}
function ExportFieldsToXml {
Param(
[string]$listTitle,
[string]$xmlFilename,
[boolean]$includeHidden = $false
)
#$list = Get-PnPList -Identity $list
if ([string]::IsNullOrEmpty($listTitle)) {
$fields = Get-PnPField
$stringBuilder = New-Object System.Text.StringBuilder
$null = $stringBuilder.AppendLine("")
for ($i = 0 ; $i -lt $fields.Length ; $i++) {
$field = $fields[$i];
$null = $stringBuilder.AppendLine($field.SchemaXml);
}
$null = $stringBuilder.AppendLine("")
$stringBuilder.ToString() | Out-File -FilePath "$($xmlFilename)" -Encodin:UTF8 -Append
}
}
function ImportFields {
Param(
[string]$listTitle,
[string]$xmlFilePath,
[boolean]$includeHidden = $false
)
[XML]$xmlfile = Get-Content -Path $xmlFilePath -Encoding:UTF8
if ([string]::IsNullOrEmpty($listTitle)) {
foreach ($field in $xmlfile.fields.Field) {
Write-Host $field.Name
$exists = Get-PnPField -Identity $field.Name -ErrorAction:SilentlyContinue
if ($null -eq $exists) {
Write-Host "$($field.Name) is null"
Add-PnPFieldFromXml -FieldXml $field.OuterXml
Write-Host "$($field.Name) added"
}
else {
Write-Host "$($field.Name) exists"
}
}
}
else {
foreach ($field in $xmlfile.fields.Field) {
$siteField = Get-PnPField -Identity $field.Name -ErrorAction:SilentlyContinue
$listField = Get-PnPField -Identity $field.Name -List $listTitle -ErrorAction:SilentlyContinue
if ($null -eq $siteField -and $null -eq $listField) {
Write-Host "$($field.Name) is null"
Add-PnPFieldFromXml -FieldXml $field.OuterXml
Add-PnPField -List $listTitle -Field $field.Name
Write-Host "$($field.Name) added"
}
elseif($null -eq $listField){
Write-Host "$($field.Name) exists"
Add-PnPField -List $listTitle -Field $siteField.InternalName
Write-Host "$($field.Name) added to $($listTitle)"
}
}
}
}
PowerAutomate Functions
By fredericdietrich On 21/04/2022
Concat
concat(outputs('Compose'),'test')
Get user mail in REST results
items('Appliquer_à_chacun')?['MyUser']?['EMail']
Add 10 Days
addDays(utcNow(),10)
Get JSON data
body('parameterJSON')?['Relaunch1nbDays']
body('myGet')?['value']
Get variable value
variables('RelaunchDate1')
Check data is empty
if(empty(variables('userMail')), null, variables('userMail'))
Date formatting
formatDateTime(your-value, 'dd/MM/yyyy hh:mm tt')
image base64 to <img>
Get_file_content_using_path_2')['$content'] //the $ is important
<img class="logo" src="data:image/jpeg;base64, @{body('Get_file_content_using_path_2')['$content']}" alt="My Image" />
Power Automate Check User Exists
By fredericdietrich On 24/01/2022
/_api/web/ensureuser
content-type application/json; odata=verbose
{'logonName': '@{variables('userMailToCheck')}'}
@{outputs('Send_an_HTTP_request_to_SharePoint')['statusCode']}
How to resolve the 5000 item limit
By fredericdietrich On 24/01/2022
var firstItems = listLocation.web.getList(listLocation.listUri).items.select("ID").top(1).orderBy("Id").get(); var lastItems = listLocation.web.getList(listLocation.listUri).items.select("ID").top(1).orderBy("Id", false).get(); if (firstItems.length === 1 && lastItems.length === 1) { const firstId: number = firstItems[0].ID; const lastId: number = lastItems[0].ID; let startId = firstId; let endId = firstId + 5000; do { let mySites: ISite[] = await listLocation.web.getList(listLocation.listUri).items .select("ID", "Title", "Url") .filter(`Id ge ${startId} and Id lt ${endId} and ProprietairesPeople/Id eq ${userId}`) .expand('ProprietairesPeople') .orderBy("Title") .top(5000) .getAll(); allMySites.push(...mySites); startId = startId + 5000; endId = endId + 5000; } while (endId < lastId); } return allMySites;
Add User To Group With Rest
By fredericdietrich On 20/09/2021
Add User To Sharepoint Group With Rest
var fdi = fdi || {};
fdi.post = function(request, data, urlWeb, retFunction, expecedcode=200, odata="verbose"){
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo?&select=FormDigestValue";
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader("Accept", "application/json; odata=nometadata");
xhr.onload = function () {
if (xhr.status === 200) {
console.log(url + " : success");
var d = JSON.parse(xhr.responseText);
console.dir(d.FormDigestValue);
var viewXml = "" +
"" +
" " +
" " +
" ";
var req = { "query" :{"__metadata": { "type": "SP.CamlQuery" }, "ViewXml": viewXml}};
var xhrPOST = new XMLHttpRequest();
var reqUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(5)/users";
//debugger;
xhrPOST.open('POST', reqUrl, true);
xhrPOST.setRequestHeader("Accept", "application/json; odata=" + odata);
xhrPOST.setRequestHeader("content-type", "application/json; odata=" + odata);
xhrPOST.setRequestHeader("X-RequestDigest", d.FormDigestValue);
console.log("onload");
xhrPOST.onload = function () {
console.log("onload ok");
console.dir(JSON.parse(xhrPOST.responseText));
}
var metadata = {
__metadata: {
'type': 'SP.User'
},
LoginName: 'i:0#.f|membership|fred.ddiet@test.com'
}; JSON.stringify(metadata)
xhrPOST.send(JSON.stringify(metadata));
console.log("sent");
}
else {
console.log("error");
console.log(xhr.status);
console.dir(xhr);
console.dir(xhr.responseText);
}
};
xhr.send();
};
fdi.post();
Powerautomate Add Comment To ListItem
By fredericdietrich On 27/05/2021
Add comment to ListItem with powerautomate (http Sharepoint request)
PowerAutomate Update ListItem HTTP REST
By fredericdietrich On 27/05/2021
Update a list item with http request with powerautomate
{
"Accept": "application/json; odata=verbose",
"content-type": "application/json; odata=verbose",
"X-HTTP-Method": "MERGE",
"If-Match": "*"
}