Powershell

Sharepoint powershell tips

PowerShell List Big Files

By 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 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'
    

Powershell Import Export Fields

By 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)"

            }
        }
    }
}

Add WebPart On Modern Page PNP Powershell

By On 07/05/2021

Add custom WebPart On Modern Page Powershell

 

List your webpart with :

$page = Get-PnPPage -Identity "aTestDisp2.aspx"

$page.AvailablePageComponents() select your webpart by name or guid

Listwp 1


param([string]$siteUrl="https://myyTenant.sharepoint.com/sites/muSite", [string]$pageName="aTestDisp2", [string]$webPartName="Test - Display Item")
clear
Connect-PnPOnline -Url $siteUrl -UseWebLogin
#set your wenpart properties
$wpProps = @{webUrl="https://myyTenantsharepoint.com/sites/muSite"
            listId="b4d5f780-bd74-4cd5-b051-fed423e43125"
            field="Title"
            itemId="1"}

#get the page
$page = Get-PnPPage -Identity $pageName

# get the target webpart
$wp = $page.AvailablePageComponents() | Where-Object {$_.Name -eq $webPartName }
if($wp -eq $null)
{
    Write-Host "webpart '$($webPartName)' not found " -ForegroundColor:Red
}
#Add webpart with default user, to column 1 in section 1
Add-PnPPageWebPart -Page $pageName -Component $wp -Section 1 -Column 1 -WebPartProperties $wpProps
Disconnect-PnPOnline

 

You can check webpart properties, in result

Wpresults

PowerShell Csom Batch Delete / delete all list items

By On 09/03/2021

Powershell CSOM clear list items / delete all items

 

 


clear
# Connect-PNPOnline -url $ProdWaveplaceURL -UseWebLogin -ErrorAction Stop
# Disconnect-PnPOnline

$listTitle = "testTaxo"
$list = Get-PnPList -Identity $listTitle -ThrowExceptionIfListNotFound


$ctx = Get-PnPContext
$page = $null
$pageNumber = 0;
$rowLimit = 100
$startDate = Get-Date
$deletedItemsCount = 0;

Do{
    $stringBuilder = New-Object System.Text.StringBuilder
 
    $stringBuilder.Append("<View scope='RecursiveAll'>") | Out-Null
    $stringBuilder.Append("<Query><Where></Where>")| Out-Null
    $stringBuilder.Append("<Orderby><Fieldref ascending='TRUE' name='ID'></Fieldref></Orderby>")| Out-Null
    $stringBuilder.Append("</Query>")| Out-Null
    $stringBuilder.Append("<Viewfields>")| Out-Null
    $stringBuilder.Append("<Fieldref name='ID' />")| Out-Null
    $stringBuilder.Append("</Viewfields>")| Out-Null
    $stringBuilder.Append("<Rowlimit paged='TRUE'>$($rowLimit)</Rowlimit>")| Out-Null
    $stringBuilder.Append("</View>")| Out-Null
    
    $spqQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
    $spqQuery.ViewXml = $stringBuilder.ToString();
    $spqQuery.ListItemCollectionPosition = $page


    $pageNumber ++;

    $spqQuery.ViewXml = $stringBuilder.ToString();
    $itemki=$list.GetItems($spqQuery); 
    $spqQuery.ListItemCollectionPosition = $itemki.ListItemCollectionPosition

    $ctx.Load($itemki)
    $ctx.ExecuteQuery();


    Write-Host "################## PAGE " $($page.PagingInfo) " #########################"
    Write-Host "processing query results. Recs: $($itemki.Count)"

    $Counter = $itemki.Count;
    if($itemki.Count -eq 0){
        exit 0
    }
    do{
        $itemki[$Counter - 1].DeleteObject()

        $Counter--
        $deletedItemsCount++
    }while($Counter -gt 0)
    Invoke-PnPQuery
    Write-Host "deletedItemsCount $($deletedItemsCount)"
    $page = $itemki.ListItemCollectionPosition
    $comp = $endDate - $startDate
    $endDate = Get-Date
    Write-Host "time to delete $($rowLimit) elements : Days '$($comp.Days)' Hours '$($comp.Hours)' Minutes '$($comp.Minutes)' Seconds '$($comp.Seconds)'"
 }   
 Until($page -eq $null) 

$comp = $endDate - $startDate
Write-Host "time to delete : Days '$($comp.Days)' Hours '$($comp.Hours)' Minutes '$($comp.Minutes)' Seconds '$($comp.Seconds)'"

Export List Fields To Csv With Pnp Powershell

By On 21/01/2021

Export List Fields To Csv With Pnp Powershell

 


param($url="https://myTestSite", $listTitle="/Lists/aList")
clear

#connect to your site using windows identity manager
Connect-PnPOnline -Url "$($url)"  -Credentials 'myWindowsOrWebIdentity'

$list = Get-PnPList -Identity $listTitle -Includes Fields


function ExctractFieldsNoContentType()
{
    param($targetList)
    $targetList.Title
   
    $toExport = @()
    for($i = 0 ; $i -lt $targetList.Fields.Count ; $i++)
    {
        $field = $targetList.Fields[$i]
        
        #put in an object some field properties
        $aFieldToExport = New-Object -TypeName PSObject -Property @{

        'Title' = $field.Title
        'InternalName' = $field.InternalName
        'TypeAsString' = $field.TypeAsString
        'Hidden' = $field.Hidden
        'Group' = $field.Group
        'Required' = $field.Required
        'Description' = $field.Description

        }
        $toExport += $aFieldToExport
    }
    #export to csv
    $toExport | Export-Csv -Path "$($targetList.Title)_fields.csv" -Encodin:UTF8 -NoTypeInformation -Delimiter ";"

}

ExctractFieldsNoContentType -targetList $list
Disconnect-PnPOnline

manage identities in 

Identitymanager

CSOM powershell SSL TSL site

By On 23/11/2019

 

Exception calling "ExecuteQuery" with "0" argument(s): "The request was aborted: Could not create SSL/TLS secure channel." SOLVED

Exception lors de l'appel de ExecuteQuery" avec 0" argument(s): La demandea été abandonnée: Impossible de créer un canal sécurisé SSL/TLS." : résolu

How to connect to a SSL/ TSL sharepoint site with CSOM in powershell

Start to call a request with your certificate

 

 
$anUrl = https://mySharepoint

$CertificateThumbprint = "53836D3C35F949959D7E4038D5D39D7B"

$response = Invoke-WebRequest -Verbose -URI $anUrl -CertificateThumbprint $CertificateThumbprint -UseDefaultCredentials -SessionVariable websession -ErrorAction:Stop

 

 

# extract cookies from your response, and isolate wich one is authentication cookie
$cookies = $websession.Cookies.GetCookies($anUrl)
$global:cookieName3= "$($cookies[$i].name)".Trim();
$global:cookieVal3 = "$($cookies[$i].value)".Trim();

 

# get correct certificate in your store
$global:cert = Get-ChildItem -Path cert:\CurrentUser\My | ?{$_.Thumbprint -eq $CertificateThumbprint}
$context987 = New-Object Microsoft.SharePoint.Client.ClientContext($anUrl);
 
# set the security protocol
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor ` [Net.SecurityProtocolType]::Tls11 -bor ` [Net.SecurityProtocolType]::Tls -bor ` [Net.SecurityProtocolType]::Ssl3

 

# add an ExecutingWebRequest event, which will be raised on each Execute query
$context987.add_ExecutingWebRequest({ })

 

# in this ExecutingWebRequest you should add the certificate to yoour request and add the authentification cookie

$request = $EventArgs.WebRequestExecutor.WebRequest

$request.ClientCertificates.Add($global:cert)
$request.CookieContainer = New-Object System.Net.CookieContainer
$c3 = New-Object System.Net.Cookie($global:cookieName3, $global:cookieVal3, "/", $global:cookieDomaine);
$request.CookieContainer.Add($c3);
$context987.Load($context987.web);
$context987.ExecuteQuery();
Write-Host "Title : $($web.Title)"

 

 

to list all your available certificate execute following script

[System.Security.Cryptography.X509Certificates.X509Store]$storeNew-Object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreName]::My, [System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser) # LocalMachine
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly);
$store.Certificates | select Thumbprint, FriendlyName, Subject

Powershell Csom Paged Caml Query

By On 18/09/2019

 


$list = Get-PnPList -Identity $listTitle -ThrowExceptionIfListNotFound

$ctx = Get-PnPContext
$page = $null
$pageNumber = 0;
$rowLimit = 200
Do{
    $stringBuilder = New-Object System.Text.StringBuilder
 
    $stringBuilder.Append("<View Scope='RecursiveAll'>") | Out-Null
    $stringBuilder.Append("<Query><Where></Where>")| Out-Null
    $stringBuilder.Append("<OrderBy><FieldRef Name='ID' Ascending='TRUE' /></OrderBy>")| Out-Null
    $stringBuilder.Append("</Query>")| Out-Null
    $stringBuilder.Append("<ViewFields>")| Out-Null
    $stringBuilder.Append("<FieldRef Name='ID' />")| Out-Null
    $stringBuilder.Append("<FieldRef Name='Title' />")| Out-Null
    $stringBuilder.Append("</ViewFields>")| Out-Null
    $stringBuilder.Append("<RowLimit Paged='TRUE'>$($rowLimit)</RowLimit>")| Out-Null
    $stringBuilder.Append("</View>")| Out-Null
    
    $spqQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
    $spqQuery.ViewXml = $stringBuilder.ToString();
    $spqQuery.ListItemCollectionPosition = $page


    $pageNumber ++;

    $spqQuery.ViewXml = $stringBuilder.ToString();
    $itemki=$list.GetItems($spqQuery); 
    $spqQuery.ListItemCollectionPosition = $itemki.ListItemCollectionPosition

    $ctx.Load($itemki)
    $ctx.ExecuteQuery();


    Write-Host "################## PAGE " $($page.PagingInfo) " #########################"
    Write-Host "processing query results. Recs: $($itemki.Count)"

    $Counter = 0;
    foreach($item in $itemki)
    {
        Write-Host "$($item["ID"]) title pageNumber '$($pageNumber)' : $($item["Title"])"
    }

    $page = $itemki.ListItemCollectionPosition
 }   
 Until($page -eq $null) 


 
get script

Add SPList With CSOM

By On 15/08/2019

function AddList()
{param($url0, $title)
 
$context0 = New-Object Microsoft.SharePoint.Client.ClientContext($url0);
 
$context0.AuthenticationMode = [Microsoft.SharePoint.Client.ClientAuthenticationMode]::FormsAuthentication
$credentials0 = New-Object Microsoft.SharePoint.Client.FormsAuthenticationLoginInfo("d03305", $mypsw);
$context0.FormsAuthenticationLoginInfo = $credentials0;
 
[Microsoft.SharePoint.Client.Web]$web0 = $context0.Web;
 
 
 
$context0.Load($web0)
$context0.Load($web0.ListTemplates)
$context0.ExecuteQuery()
 
$template = $web0.ListTemplates | Where-Object {$_.Name -eq "Fiche de conformité"}
$template.Name
 
#check if list exists
$list = $null;
try
{
$list = $web0.GetList("$($web0.ServerRelativeUrl.TrimEnd("/"))/$($title)");
$context0.Load($list);
$context0.ExecuteQuery();
}
catch
{
$list = $null;
}
if($list -eq $null)
{
Write-Host "list is null"
#creation de la liste
$ListInfo = New-Object Microsoft.SharePoint.Client.ListCreationInformation
$ListInfo.Title = $title
[System.Int32]$lstId = 100#$template.ListTemplateTypeKind;
$ListInfo.TemplateType = $lstId;
$List1 = $web0.Lists.Add($ListInfo);
<#
$List1.Description = "$($title) GED Corporate";
$List1.Update()
#>
$context0.ExecuteQuery()
 
}
else
{
Write-Host "list is not null"
}
 
$list.Title;
 
$context0.Dispose();
$context0 = $null;
}

Change Files Extentsions

By On 23/11/2018

#Retourne le chemin
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
$ScriptDirectory = Get-ScriptDirectory
"$($ScriptDirectory)\Powershell" | Push-Location
 
 
Dir *.ps1 | rename-item -newname { [io.path]::ChangeExtension($_.name, ".txt") }

Powershell Paged Caml Query

By On 16/11/2018

param(
[string]$siteCollUrl = "http://test/sites/site1/",[string]$listTitle="Stockage",
[boolean]$checkin=$false,[boolean]$publish=$false, [boolean]$deleteAllVersion=$true
)
$web = Get-SPWeb $siteCollUrl
$splList = $web.Lists[$listTitle]
$spqQuery = New-Object Microsoft.SharePoint.SPQuery
$spqQuery.Query = "<Where><Neq><FieldRef Name='_Level' /><Value Type='Number'>1</Value></Neq></Where><OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy>";
 
$spqQuery.ViewAttributes = "Scope=""RecursiveAll""";
$spqQuery.ViewFields = "<FieldRef Name='FileLeafRef' /><FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='owshiddenversion' /><FieldRef Name='_Level' /><FieldRef Name='_IsCurrentVersion' /><FieldRef Name='_UIVersion' />" #_UIVersionString
$spqQuery.ViewFieldsOnly = $true
 
$spqQuery.RowLimit = 1000;
 
# IsCheckedoutToLocal
$iNumber=1
do{
if($iNumber -eq 1)
{
$spqQuery.ListItemCollectionPosition = $splListItems.ListItemCollectionPosition;
}
$splListItems = $splList.GetItems($spqQuery)
writeInfo "page number : $($iNumber)"
foreach ($splListItem in $splListItems)
{
 
writeInfo "web $($web.ServerRelativeUrl) splList $($splList.RootFolder.ServerRelativeUrl) File id : $($splListItem.Id) # $($splListItem.Name) Title: $($splListItem["Title"]) Version: $($splListItem["owshiddenversion"]) _Level: $($splListItem["_Level"]) _IsCurrentVersion: $($splListItem["_IsCurrentVersion"]) _UIVersion: $($splListItem["_UIVersion"]) ver count : $($splListItem.File.Versions.Count)"
#check in file
try
{
if($checkin)
{
$splListItem.File.CheckIn("CheckIn as admin");
}
}
catch
{
WriteError "error CheckIn web $($web.ServerRelativeUrl) splList $($splList.RootFolder.ServerRelativeUrl) File id : $($splListItem.Id) "
}
#publish file
try
{
if($publish)
{
$splListItem.File.Publish("Publish as admin");
}
}
catch
{
WriteError "error Publish web $($web.ServerRelativeUrl) splList $($splList.RootFolder.ServerRelativeUrl) File id : $($splListItem.Id) "
}
#this is a folder
if($splListItem.ContentTypeId.ToString() -eq "0x00C2208B8CE6E1422CADC1C521EAB2A68B")
{
writeInfo "folder file $($splListItem.File.ServerRelativeUrl)"
continue
}
#delete old versions
if($deleteAllVersion -and $splListItem.File -ne $null -and $splListItem.File.Versions -ne $null -and $splListItem.File.Versions.Count -gt 1)
{
$splListItem.File.Versions.DeleteAll();
writeInfo "versions deleted for $($web.ServerRelativeUrl) splList $($splList.RootFolder.ServerRelativeUrl) File id : $($splListItem.Id)"
}
}
$iNumber+=1
$spqQuery.ListItemCollectionPosition = $splListItems.ListItemCollectionPosition;
}while($spqQuery.ListItemCollectionPosition -ne $null)
 
 
$web.Dispose()
 

get script

utils

Set Content Type Field Property

By On 22/10/2018

param([string]$webUrl="http://spdev", [string]$contentTypeName="myContenttype", [string]$fieldName="myTitle", [boolean]$required=$true)
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
clear
$web = Get-SPWeb $webUrl
$ct = $web.ContentTypes[$contentTypeName];
$oldSealedValue = $ct.Sealed;
Write-Host "content type Sealed Property $($ct.Sealed)"
if($ct.Sealed)
{
$ct.Sealed = $false;
}
$field = $ct.FieldLinks[$fieldName];
$field.Required = $required;
Write-Host "set field $($fieldName) Required $($ct.Required)"
 
if($oldSealedValue)
{
$ct.Sealed = $true;
}
$ct.Update($true);
$web.Update();
$web.Dispose();
get script

Powershell Upgrade SPFeature

By On 12/10/2018

param(
[string]$WebApplicationUrl = "http://fdi-sp2013-1",
$featureId = "6cfcd848-1f9f-4bf0-ac99-c6f2df0fc3fc"
)
##########################################################################
# DECLARATIONS
##########################################################################
#Retourne le chemin
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Get-ScriptDirectory | Push-Location
. .\Utils.ps1
$logFileName = "{0}updateFeature.log" -f (Get-Date -Format "yyyyMMdd_HHmm");
$logFilePath = "$($currentFolder)\Logs\UpgradeFeaturePublishing$($logFileName)"
EnsureLogDirectory $logFilePath
##########################################################################
# MAIN
##########################################################################
$currentUrl = "";
try{
if ($WebApplicationUrl -eq ""){
$WebApplicationUrl = AskForWebApplicationUrl
}
$webApp=Get-SPWebApplication $WebApplicationUrl
$webApp.Sites|Foreach-Object{
$spSite=$_
WriteInfo "Site: $($spSite.Url)"
$site=Get-SPSite $spSite.Url
if($site -ne $null)
{
$feature=Get-SPFeature $featureId
if($feature -ne $null){
$featuresForUpgrade = Get-SPSite $spSite.Url | %{$_.QueryFeatures($feature.Id)}
if($featuresForUpgrade -ne $null){
WriteInfo "Old Version..."
$featuresForUpgrade.Version
$featuresForUpgrade.Upgrade($false)
WriteInfo "New Version..."
$featuresForUpgrade.Version
}
}
}
}
Write-Host -NoNewLine 'Press any key to close...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
}catch{
Write-Error -Message $_.Exception.Message
Write-Host -NoNewLine 'Press any key to close...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
}finally{
Pop-Location
}

get script

Powershell Get SPList Last Modified

By On 11/10/2018

param($webUrl="http://fdi-sp2013-1:2921", [string]$listTitle="Pages")
 
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell
}
clear;
$web = Get-SPWeb $webUrl
$list = $web.Lists[$listTitle]
$list.PropertiesXml
 
$props = New-Object System.Xml.XmlDocument
$props.LoadXml($list.PropertiesXml)
 
$props.ChildNodes
 
$web.Dispose()
 
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

get script

Listlastmodified

Add task to reset sharepoint search index with powershell

By On 05/10/2018

Create a powershell script (task1.ps1) with code below


if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell -Verbose -ErrorAction:Stop
}
#the $True parameter denotes: Disable Alerts and Ignore Timeout error.
(Get-SPEnterpriseSearchServiceApplication).reset($true, $true)

Add a new task in your task scheduler

Check the radio button 'Run whether user is logged on or not

Set a name and add a trigger to set scheduling

set the action : program / script

	
		%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
	
	

argument with -command followed by the pass to your powershell script

	
		-executionpolicy unrestricted -command D:\PS1\Task1.ps1
	
	

Save your task

 

reset indexes of one content source only

PowerShell Export List Fields To Xml

By On 01/10/2018

param([string]$webUrl=http://fdi-sp2013-1,
[string]$listUrl="Lists/myList",
[string]$contentTypeName,
[boolean]$includeHiddenFields=$true,
[string]$excludeTypes="Computed;Lookup;Guid"
)
clear
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Push-Location
 
function AddType($typeAsString)
{
$types = $excludeTypes.Split(";");
return $types.Contains($typeAsString) -eq $true;
}
function AddField($field)
{
<##>
if(AddType($field.TypeAsString) -eq $false)
{
return;
}
 
$fields = $script:exportNode.SelectSingleNode("/List/Fields");
[System.XML.XMLElement]$oXMLField=$global:exportNode.CreateElement("Field");
#InternalName
$urlAt = $global:exportNode.CreateAttribute("InternalName");
$urlAt.Value = $field.InternalName;
$oXMLField.Attributes.Append($urlAt);
$fields.AppendChild($oXMLField);
#Title
$urlAt = $global:exportNode.CreateAttribute("Title");
$urlAt.Value = $field.Title;
$oXMLField.Attributes.Append($urlAt);
$fields.AppendChild($oXMLField);
#TypeAsString
$urlAt = $global:exportNode.CreateAttribute("TypeAsString");
$urlAt.Value = $field.TypeAsString;
$oXMLField.Attributes.Append($urlAt);
$fields.AppendChild($oXMLField);
#Hidden
$urlAt = $global:exportNode.CreateAttribute("Hidden");
$urlAt.Value = $field.Hidden;
$oXMLField.Attributes.Append($urlAt);
$fields.AppendChild($oXMLField);
#Required
$urlAt = $global:exportNode.CreateAttribute("Required");
$urlAt.Value = $field.Required;
$oXMLField.Attributes.Append($urlAt);
#Group
$urlAt = $global:exportNode.CreateAttribute("Group");
$urlAt.Value = $field.Group;
$oXMLField.Attributes.Append($urlAt);
$fields.AppendChild($oXMLField);
<# #>
}
 
$web = Get-SPWeb $webUrl -ErrorAction:SilentlyContinue;
if($web -eq $null)
{
read-Host "cannot access to $($webUrl) push any key to exit"
exit 0;
}
Write-Host "connected to $($webUrl) Title $($web.Title)"
 
$list = $web.GetList([Microsoft.Sharepoint.Utilities.SPUtility]::ConcatUrls($web.ServerRelativeUrl, $listUrl));
Write-Host "list $($list.Title) loaded"
 
#create xml document
$global:exportNode = New-Object System.Xml.XmlDocument
 
#add list node
[System.XML.XMLElement]$oXMLRoot=$global:exportNode.CreateElement("List")
 
 
#web Url attribute
$urlAt = $global:exportNode.CreateAttribute("url");
$urlAt.Value = $webUrl;
$oXMLRoot.Attributes.Append($urlAt);
 
#web title attribute
$urlAt = $global:exportNode.CreateAttribute("webTitle");
$urlAt.Value = $web.Title;
$oXMLRoot.Attributes.Append($urlAt);
 
#List Title attribute
$urlAt = $global:exportNode.CreateAttribute("ListTitle");
$urlAt.Value = $list.Title;
$oXMLRoot.Attributes.Append($urlAt);
 
#List Url attribute
$urlAt = $global:exportNode.CreateAttribute("ListUrl");
$urlAt.Value = $listUrl;
$oXMLRoot.Attributes.Append($urlAt);
 
#add list note to xmlDocument
$global:exportNode.appendChild($oXMLRoot);
 
$fields = $null;
 
if($includeHiddenFields)
{
$fields = $list.Fields |Sort-Object{$_.InternalName} | select Title, InternalName, TypeAsString, Hidden, Required, Group
}
else
{
$fields = $list.Fields |Sort-Object{$_.InternalName} | Where-Object {$_.Hidden -eq $false} | select Title, InternalName, TypeAsString, Hidden, Required, Group
}
 
#add fields
[System.XML.XMLElement]$oXMLFields=$global:exportNode.CreateElement("Fields")
$global:exportNode.FirstChild.AppendChild($oXMLFields);
foreach($field in $fields){
AddField($field);
}
 
#add ContentTypes
[System.XML.XMLElement]$oXMLContentTypes=$global:exportNode.CreateElement("ContentTypes")
$global:exportNode.FirstChild.AppendChild($oXMLContentTypes);
 
$oXMLContentTypes = $script:exportNode.SelectSingleNode("/List/ContentTypes");
 
foreach($contentType in $list.ContentTypes)
{
[System.XML.XMLElement]$oXMLContentType=$global:exportNode.CreateElement("ContentType");
$urlAt = $global:exportNode.CreateAttribute("Name");
$urlAt.Value = $contentType.Name;
$oXMLContentType.Attributes.Append($urlAt);
 
$oXMLContentTypes.AppendChild($oXMLContentType);
 
 
[System.XML.XMLElement]$oXMLCTFields=$global:exportNode.CreateElement("Fields");
$oXMLContentType.AppendChild($oXMLCTFields);
<##>
if($includeHiddenFields)
{
$fields = $contentType.Fields |Sort-Object{$_.InternalName} | select Title, InternalName, TypeAsString, Hidden, Required, Group
}
else
{
$fields = $contentType.Fields |Sort-Object{$_.InternalName} | Where-Object {$_.Hidden -eq $false} | select Title, InternalName, TypeAsString, Hidden, Required, Group
}
 
 
#fields in content type
foreach($field in $fields)
{
[System.XML.XMLElement]$oXMLCTField=$global:exportNode.CreateElement("Field");
#InternalName
$urlAt = $global:exportNode.CreateAttribute("InternalName");
$urlAt.Value = $field.InternalName;
$oXMLCTField.Attributes.Append($urlAt);
#Title
$urlAt = $global:exportNode.CreateAttribute("Title");
$urlAt.Value = $field.Title;
$oXMLCTField.Attributes.Append($urlAt);
#TypeAsString
$urlAt = $global:exportNode.CreateAttribute("TypeAsString");
$urlAt.Value = $field.TypeAsString;
$oXMLCTField.Attributes.Append($urlAt);
#Hidden
$urlAt = $global:exportNode.CreateAttribute("Hidden");
$urlAt.Value = $field.Hidden;
$oXMLCTField.Attributes.Append($urlAt);
#Required
$urlAt = $global:exportNode.CreateAttribute("Required");
$urlAt.Value = $field.Required;
$oXMLCTField.Attributes.Append($urlAt);
#Group
$urlAt = $global:exportNode.CreateAttribute("Group");
$urlAt.Value = $field.Group;
$oXMLCTField.Attributes.Append($urlAt);
 
$oXMLCTFields.AppendChild($oXMLCTField);
 
}
}
<# #>
#export to test file
$global:exportNode.OuterXml | Out-File "$($list.Title.Replace(" ", "_")).xml" -Encoding utf8
 
#dispose the web
$web.Dispose()

download file

Sharepoint PowerShell query search service

By On 29/09/2018

SharePoint PowerShell query search service

param([string]$siteCollectionUrl="http://mySiteUrl" ,
$keyword="ContentTypeId:0x010100020D149374FFC4DF792F30EFC030C9D01* ",
$rowLimit=500,
$SelectProperties="Title,SPWebUrl,Path"
)
 
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
$site = Get-SPSite $siteCollectionUrl
$keywordQuery = New-Object Microsoft.Office.Server.Search.Query.KeywordQuery($site);
 
#set request
$keywordQuery.QueryText = $keyword
 
#set managed properties to retreive
foreach($mnp in $SelectProperties.Split(","))
{
$keywordQuery.SelectProperties.Add($mnp.Trim());
}
$keywordQuery.RowLimit = $rowLimit
 
$searchExec = New-Object Microsoft.Office.Server.Search.Query.SearchExecutor
$searchResults = $searchExec.ExecuteQuery($keywordQuery)
 
#display results
$table = $searchResults.Table
$table | Select Title, SPWebUrl, Path
 
$site.Dispose()

Sharepoint Execute Job With Powershell

By On 28/09/2018

$webApplication = Get-SPWebApplication $siteUrl
$jobName = "lmlhmohmo"
$variationsJob = $webApplication.JobDefinitions | Where {$_.Name -like "$($jobName)*"}
Get-Date
foreach($job in $variationsJob)
{
$lastRunTime = $job.LastRunTime
$job.RunNow()
Write-Host $job.Name + " - " + $job.LastRunTime + " - " + $siteUrl + " - " + $job.Title
 
while ($lastRunTime -eq $job.LastRunTime){
Write-Host -NoNewline "."
Start-Sleep -Seconds 5
}
}
Get-Date

Sharepoint Powershell Clear Search Cache

By On 28/09/2018

Stop-Service SPTimerV4
$folders = Get-ChildItem C:\ProgramData\Microsoft\SharePoint\Config
foreach ($folder in $folders)
{
$items = Get-ChildItem $folder.FullName -Recurse
foreach ($item in $items)
{
if ($item.Name.ToLower() -eq "cache.ini")
{
$cachefolder = $folder.FullName
}
}
}
$cachefolderitems = Get-ChildItem $cachefolder -Recurse
foreach ($cachefolderitem in $cachefolderitems)
{
if ($cachefolderitem -like "*.xml")
{
$cachefolderitem.Delete()
}
}
 
$a = Get-Content $cachefolder\cache.ini
$a = 1
Set-Content $a -Path $cachefolder\cache.ini
 
read-host "Do this on all your SharePoint Servers and THEN press ENTER"
Start-Service SPTimerV4

Powershell Batch Delete

By On 28/09/2018

param($url="http://fdi-sp2013-1:8080/sites/testJS_publishing2",
$listTitle="testDelete")
 
clear;
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
#get the spweb
$web = Get-SPWeb -Identity $url
#get list by title
$list = $web.Lists[$listTitle];
$list.Title
 
#your caml query
$query = New-Object -TypeName Microsoft.SharePoint.SPQuery
$rowLimit= 100
 
$query.ViewXml = "<View><ViewFields><FieldRef Name='ID'><FieldRef Name='FileRef'></FieldRef></FieldRef></ViewFields><Query><Where></Eq></Where></Query><RowLimit>$($rowLimit)</RowLimit></View>";
 
$items = $list.GetItems($query)
 
#number items
"items.Count : $($items.Count)"
 
#the number of items that will be deleted
$batch = "<?xml version=""1.0"" encoding=""UTF-8""?><Batch>";
foreach($item in $items)
{
$batch +="<Method><SetList Scope=""Request"">$($list.ID)</SetList><SetVar Name=""ID"">$($item.Id)</SetVar><SetVar Name=""owsfileref"">$($item["FileRef"])</SetVar><SetVar Name=""Cmd"">Delete</SetVar></Method>"
$item.Id
$item["FileRef"]
}
$batch +="</Batch>"
 
#proceed to deletion
$web.ProcessBatchData($batch);
$web.Dispose()
Write-Host "list is empty bu warnig limit in code rowLimit $($rowLimit)"

Sharepoint Powershell tips

By On 28/09/2018

To add your assembly in powershell script / console

Add-Type -AssemblyName System.Web

 

Copy string to clipboard

"your datas" | c:\windows\system32\clip.exe

 

Reference sharepoint in powershell console

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

 

Set your execution policy if you see this message

Impossible de charger le fichier D:\FDI\wordPress\ps1\EncodeHtml.ps1, car l’exécution de scripts est désactivée sur ce système. Pour plus
d’informations, consultez about_Execution_Policies à l’adresse https://go.microsoft.com/fwlink/?LinkID=135170.
+ CategoryInfo : Erreur de sécurité : (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnauthorizedAccess

set-executionpolicy -executionpolicy unrestricted

powershell.exe -executionpolicy unrestricted -command .\test.ps1

 

Sort and filter your collections

$l.Fields | select internalname, title, type, hidden | Where-Object {$_.Hidden -eq $false} | Sort-Object -Property internalname | Format-Table

get spfields by group

$w.Fields | Where-Object {$_.Group -eq "Site colums FDI"} | select internalName, typeasstring

List files in folder and copy to clipboard

$files = ls | select name

$files | c:\windows\system32\clip.exe

 

Regular expression to check file names

"toto.spx" -match "^[a-zA-Z0-9._ -]+$"

 

Load an assembly

Import-Module ".\Microsoft.SharePoint.Client.Runtime.dll"

 

Get logs from all servers on sharepoint farm

Merge-SPLogFile -Path "C:\temp\FarmMergedLog41.log" -Overwrite -Level Unexpected -StartTime (Get-Date).AddMinutes(-20)

Merge-SPLogFile -Path "C:\temp\FarmMergedLog22.log" -Overwrite -Correlation "52b2019e-d446-70aa-8f27-8efc5ec7f143" -StartTime (Get-Date).AddMinutes(-90)

 

Open a powershell console as another account

Start-Process powershell.exe -Credential "domain\spadmin" -NoNewWindow -ArgumentList "Start-Process powershell.exe -Verb runAs"

 

Export webpart from page

http://fdi-sp2013-1/_vti_bin/exportwp.aspx?pageurl=http://fdi-sp2013-1/Lists/Pratique/PratiqueHome.aspx&guidstring=84e04c62-3eb5-424e-a7f9-3219ff89d51c

 

Create a site collection

New-SPSite -Template STS#0 -OwnerAlias fdi\spdev -Url http://fdi-sp2013-1/sites/test6541 -Verbose -Confirm:$false -Language 1036 -Name test987 -Description oio

 

Do not use jquery $(document).ready(function () {

Use instead :

_spBodyOnLoadFunctionNames.push("loadAnnonce");//loadAnnonce is function loadAnnonce() called

 

Edit page on url change

?ControlMode=Edit&DisplayMode=Design

 

List assemblies

[AppDomain]::CurrentDomain.GetAssemblies() | Where-Object {$_.Location -ne $null -and $_.Location -like "*t.Client.*"}

 

Use stringBuilder to mange string concat

$stringBuilder = New-Object System.Text.StringBuilder

 

List of all sharepoint features

csv format

xlsx format