powershell icon indicating copy to clipboard operation
powershell copied to clipboard

[BUG] Azure Runbook: Write-Output $Connection -> "The Push Notifications feature is not activated" / "The property or field 'WelcomePage' has not been initialized

Open Henry-Sir opened this issue 1 year ago • 2 comments

Reporting an Issue or Missing Feature

Multiple errors after "Write-Output $Connection" when executing Invoke-PnPSiteTemplate in Azure Automation Runbook. This error only occurs in the runbook, not when executed locally! All errors do not occur if the "$Connection" is not output.

Expected behavior

No errors

Actual behavior

  • Connect to SharePoint site with "ReturnConnection" (Connect-PnPOnline -ReturnConnection)
  • Write-Output the "Connection" variable
  • Invoke-PnPSiteTemplate has mutiple errors: 1st error: "The Push Notifications feature is not activated on the site" 2nd error: Activation of the Push Notifications service (Enable-PnPFeature -Identity 41e1d4bf-b1a2-47f7-ab80-d5d6cbba3092) -> "Object reference not set to an instance of an object." This error only occurs if the pnp:Security element is included in the page template 3rd error: "The property or field 'WelcomePage' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested." This error only occurs if the "WelcomePage" parameter in pnp:WebSettings element is included in the page template.

image image image

Steps to reproduce behavior

Here the script to run in Azure Runbook In the KeyVault ist the certificat and the AppId of the service principal. The KeyVault name is stored in the automation varaible.

Param
(
  [Parameter (Mandatory= $false)]
  [String] $siteName,
  [Parameter (Mandatory= $false)]
  [bool]$OnlyTemplate
)


If($PSVersionTable.PSVersion.Major -eq 5){Import-Module -Name PnP.PowerShell -RequiredVersion 1.12.0 }Else{Import-Module -Name PnP.PowerShell }
Get-Module PnP.PowerShell

# Connecting to Azure via  Connect-AzAccount -Identity" -> Runbook directly without hybrid worker
Write-Output "Connect to Azure"
#Disable-AzContextAutosave -Scope Process | Out-Null
$AzCon = Connect-AzAccount -Identity

Write-Output "Get KeyVault information"
# KeyVault
$azureKeyVaultName = Get-AutomationVariable -Name "KeyVaultName"
# SharePoint
[string]$SPOAdminUrl = Get-AzKeyVaultSecret -VaultName $azureKeyVaultName -Name "SPOAdminUrl" -AsPlainText

$azureCert = Get-AzKeyVaultCertificate -VaultName $azureKeyVaultName -Name "SPOCertificate"
$certBase64 = Get-AzKeyVaultSecret -VaultName $azureKeyVaultName -Name $azureCert.Name -AsPlainText
$AppID = Get-AzKeyVaultSecret -VaultName $azureKeyVaultName -Name "SPOAppID" -AsPlainText	

$SiteAdmin = Get-AutomationVariable -Name "spDefaultSiteAdmin"

Write-Output "Set config"
if(!$siteName){$siteName = "Workshop" + (Get-Date -Format "yyyy-dd-MM-HHmmss")}
$siteUrl = $SPOAdminUrl.Replace("-admin.sharepoint.com",".sharepoint.com") + "/sites/$siteName"
$orgName =  ($SPOAdminUrl.Replace("https://","").Replace("http://","").Split(".")[0]).Replace("-admin","").Replace("-my","")
$aadDomain = "$orgName.onmicrosoft.com"
$siteTitle = $siteName
$siteLcid = 1033
$siteType = "STS#3"
$siteTimeZone = 4
$siteSharing = "ExistingExternalUserSharingOnly"    # "Disabled"
$Owner = Get-AutomationVariable -Name "spDefaultSiteAdmin"
$SiteAdmin = Get-AutomationVariable -Name "spDefaultSiteAdmin"


$template = '<?xml version="1.0" encoding="utf-8"?>
<pnp:Provisioning xmlns:pnp="http://schemas.dev.office.com/PnP/2022/09/ProvisioningSchema">
  <pnp:Preferences Generator="PnP.Framework, Version=1.14.3.0, Culture=neutral, PublicKeyToken=0d501f89f11b748c" />
  <pnp:Templates ID="CONTAINER-TEMPLATE-C26B54B82DB5445F88A4D4DFF622DFD5">
    <pnp:ProvisioningTemplate ID="TEMPLATE-C26B54B82DB5445F88A4D4DFF622DFD5" Version="1" BaseSiteTemplate="STS#3" Scope="RootSite">
      <pnp:WebSettings WelcomePage="SitePages/Home.aspx" />
	  <pnp:Security>
        <pnp:AdditionalAdministrators ClearExistingItems="false">
          <pnp:User Name="{parameter:Administrators}" />
        </pnp:AdditionalAdministrators>
        <pnp:AdditionalOwners ClearExistingItems="true"> 
            <pnp:User Name="{parameter:Owner}" />
        </pnp:AdditionalOwners>
      </pnp:Security>
	  <pnp:ClientSidePages>
        <pnp:ClientSidePage PromoteAsNewsArticle="false" PromoteAsTemplate="false" Overwrite="true" Layout="Home" EnableComments="false" Title="Homepage" ThumbnailUrl="" PageName="Home.aspx">
          <pnp:Header Type="Default" LayoutType="FullWidthImage" ShowTopicHeader="false" ShowPublishDate="false" ShowBackgroundGradient="false" TopicHeader="" AlternativeText="" Authors="" AuthorByLine="" AuthorByLineId="-1" />
          <pnp:Sections>
            <pnp:Section Order="1" Type="OneColumn" BackgroundEmphasis="Neutral">
            </pnp:Section>
		  </pnp:Sections>
        </pnp:ClientSidePage>
      </pnp:ClientSidePages>
    </pnp:ProvisioningTemplate>
  </pnp:Templates>
</pnp:Provisioning>'

$templateFile = $env:TEMP + "\" +  (New-Guid).ToString() + ".xml"
$logFile = $templateFile.Substring(0,$templateFile.LastIndexOf("\")+1) + "Trace.log"

												# Email
$OwnerName = (Get-Culture).TextInfo.ToTitleCase($Owner.ToLower().Split("@")[0].Replace("."," "))	# Name
$OwnerPrincipal = "i:0#.f|membership|" + $Owner;



If(!$OnlyTemplate){
	$Connection = Connect-PnPOnline   	-CertificateBase64Encoded $certBase64 `
										-Tenant $aadDomain `
										-ClientId $AppID `
										-Url $SPOAdminUrl `
										-TenantAdminUrl $SPOAdminUrl `
										-ReturnConnection `
										-ErrorAction Stop


	Try{
		New-PnPTenantSite -Title $siteTitle -Url $siteUrl -Owner $SiteAdmin -Lcid $siteLcid -Template $siteType -TimeZone $siteTimeZone -Wait -Connection $Connection
				
		#check status of site, timeout 120 sek.
		$i = 0
		$pnpSiteActive = $false
		Do{
			Write-Output "Check status of $siteUrl"
			$pnpSite = Get-PnPTenantSite -Identity $siteUrl -ErrorAction SilentlyContinue -Connection $Connection
			
			if ($null -eq $pnpSite){
				throw "Error occured Teamsite $siteUrl can not be created"
			}
			
			If($pnpSite.Status -eq "Active"){
				Write-Output "$siteUrl is active"
				$pnpSiteActive = $true
				
			}
			$i += 1
			Start-Sleep -Seconds 10
		}Until($pnpSiteActive -or $i -ge 12)
		
		
		#set primary administrator if not set
		If($pnpSite.Owner -ne $SiteAdmin){
			Write-Output "Set primary administrator of $siteUrl to $SiteAdmin. Currently, is '$($pnpSite.OwnerName)' set as owner."
			Set-PnPTenantSite -Identity $siteUrl -Owners $SiteAdmin -Wait -Connection $Connection
		} 
		
		#set sharing settings
		Write-Output "Set sharing settings of $siteUrl to $siteSharing"
		Set-PnPTenantSite -Identity $siteUrl -SharingCapability $siteSharing -Wait -Connection $Connection -ErrorAction Stop
		

		Write-Output "Teamsite creation $siteUrl executed"
	} catch {
		Write-Error "Error occured while creating teamsite $siteUrl : $PSItem"
		throw [System.Exception]::new('Creating of teamsite failed', $PSItem.Exception)
	}
	finally {
		Try{Disconnect-PnPOnline -Connection $Connection -ErrorAction Ignore | Out-Null}Catch{}
		Write-Output "Disconnected from $SPOAdminUrl"
	}
} Else {
    $pnpSiteActive = $true
}




If($pnpSiteActive){

    $template | Out-File -FilePath $templateFile -Force -Encoding utf8

    Write-Output "Applying the template to site $siteUrl"
    Write-Output "Template File:" (Get-Item $templateFile)
	Write-Output "Log File: $logFile"
    
    $Connection = Connect-PnPOnline   	-CertificateBase64Encoded $certBase64 `
										-Tenant $aadDomain `
										-ClientId $AppID `
										-Url $siteUrl `
										-TenantAdminUrl $SPOAdminUrl `
										-ReturnConnection `
										-ErrorAction Stop
    
    Write-Output $Connection
    
    Try{
        Set-PnPTraceLog -On -Level Debug -WriteToConsole -LogFile $logFile 

		$parameters = @{};
		if($SiteAdmin) { $parameters.Add("Administrators", $SiteAdmin) }
		if($Owner) { $parameters.Add("Owner", $Owner) }

        Write-Output "Parameters" $parameters

        Invoke-PnPSiteTemplate -Path $templateFile -Parameters $parameters -Connection $Connection
    } Catch {
        Write-Output "Applying the template failed:"
        Get-PnPException
    } Finally {
        Set-PnPTraceLog -Off;
        Try{Disconnect-PnPOnline -Connection $Connection -ErrorAction Ignore | Out-Null}Catch{}
        Write-Output "Disconnected from $siteUrl"

		Write-Output "LogFile Content:"
		Get-Content $logFile
    }
}

What is the version of the Cmdlet module you are running?

Azure Runbook PowerShell 7.2 and PnP.PowerShell 2.3.0

Which operating system/environment are you running PnP PowerShell on?

  • [x] Windows
  • [ ] Linux
  • [ ] MacOS
  • [ ] Azure Cloud Shell
  • [ ] Azure Functions
  • [x] Azure Runbook

Henry-Sir avatar Feb 05 '24 10:02 Henry-Sir

Not sure if the problem is related, but I'm also experiencing random "The Push Notifications feature is not activated on the site" errors. I say random as they happen intermittently on various cmdlets and then suddenly resolves.

iamperson347 avatar Feb 27 '24 18:02 iamperson347

I had the same issue but was unable to find the root cause. In SharePoint admin center push notification is enabled. So I fixed it dirty: $pushNotificationFeature = "41e1d4bf-b1a2-47f7-ab80-d5d6cbba3092" $FeatureTest = Get-PnPFeature -Identity $pushNotificationFeature if ($FeatureTest.DefinitionId -ne $pushNotificationFeature){ #Write-Output "The Push Notifications feature is not activated on this site, activating.." Enable-PnPFeature -Identity $pushNotificationFeature #Write-Output "The Push Notification feature has been activated." }

jonas-claes avatar Mar 15 '24 11:03 jonas-claes