June 9, 2015

SharePoint: Create Publishing page with specific Modified date using PowerShell

Problem

I had to import thousands of lines from CSV file and turn those into SharePoint publishing pages. Overall, it was easy with PowerShell, but whenever I used $item.File.Publish("") at the end of creating new Publishing Page to publish it, the Modified date was set to current date and time. I tried all possible variations and tricks I could come up with until I came up with the solution.

Solution

You need to turn off minor versioning for the Pages list and only call CheckIn for the individual items. Doing CheckIn doesn't touch the Modified date. After you've imported all items, you can enable minor versioning on the list, and all items will remain published.

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

$web = Get-SPWeb https://sharepoint.mydomain.com/m/nf/0
$list = $web.Lists["Pages"]

#Important to disable this first to get rid of
$list.EnableMinorVersions = $false
$list.EnableVersioning = $false
$list.Update()

# Change it to real layout name
$PageLayout =  $pweb.GetAvailablePageLayouts() | Where-Object {$_.ServerRelativeUrl -eq "/m/nf/_catalogs/masterpage/myportal/article.aspx"}

# Imports modified Rawdata from CSV file to MiPages - change filename if needed
Import-Csv -Delimiter ";" -Path (Resolve-Path RawData.csv) | ForEach-Object {
   
    # Page title
    $PageTitle = $_.Title
   
    # Place to save news, filename format is i+ID.aspx
    $PageUrl = "i" + [string]$_.ID + ".aspx"
   
    $SourceDate = Get-Date $_.Date

    Write-Host "Creating $($PageUrl)"

    # Create blank page
    $page = $pWeb.AddPublishingPage($PageUrl,$PageLayout)
       
    # Sets listitem fields
    $item = $page.ListItem
    $item["Title"] = $PageTitle
    $item["Created"] = $SourceDate
    $item["Modified"] = $SourceDate

    # Update list items
    $item.UpdateOverwriteVersion()

    # Check-in and publish page  
    $page.CheckIn("")      
}

$list.EnableMinorVersions = $true
$list.EnableVersioning = $true
$list.Update()

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete