If I execute the following through a PowerShell console (ran manually) I am able to get the webParts to work correctly:

$list = $context.web.Lists.GetByTitle("Pages du site")
$pages = $list.RootFolder.Files
$page = $list.RootFolder.Files | Where {$_.Name -eq "Accueil.aspx"}
$wpm = $page.GetLimitedWebPartManager("Shared")
$webParts = $wpm.WebParts

$xmlDocument = Get-Content -Path "C:\Users\<censored>\desktop\table_matieres.webpart" -Raw
$xmlDocument1 = Get-Content -Path "C:\Users\<censored>\desktop\flux_site.dwp" -Raw

$wpManager = $page.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$importWP = $wpManager.ImportWebPart($xmlDocument)
$importWP1 = $wpManager.ImportWebPart($xmlDocument1)

$wp = $wpManager.AddWebPart($importWP.WebPart,"wpz",0)
$wp1 = $wpManager.AddWebPart($importWP1.WebPart,"wpz",0)

However, if I run the exact same commands in a PS1 script, I get the following error:

The file you imported is not valid. Verify that the file is a Web Part description file (*.webpart or *.dwp) and that it contains well-formed XML.

There must be a valid reason for this, which I was not able to find yet (after searching around the web). I did try to change some lines to add "[xml]" such as:

[xml]$xmlDocument = Get-Content -Path "C:\Users\<censored>\desktop\table_matieres.webpart" -Encoding UTF8
[xml]$xmlDocument1 = Get-Content -Path "C:\Users\<censored>\desktop\flux_site.dwp" -Encoding UTF8


$xmlDocument = [xml](Get-Content -Path "C:\Users\<censored>\desktop\table_matieres.webpart")
$xmlDocument1 = [xml](Get-Content -Path "C:\Users\<censored>\desktop\flux_site.dwp")

But I am still always getting the same error message.

I suspect that a PS1 script validates the webParts differently (or the XML files).

What needs to be changed for the same commands to work in a PS1 script please?

Thank you for your time and help, it's always appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.