我正在尝试使用 powershell 从 sharepoint 文档库中操作 xml 文件。不幸的是,我无法打开它并将其转换为 xml。:( 我在文档库和本地硬盘驱动器上有相同的文件。当我从硬盘驱动器打开它时,一切都很好。当我从 Sharepoint 文档库打开它时,由于开头有一个额外字符,转换为 xml 失败文件。我二进制比较了 $splistitem.File.OpenBinary() 和 get-content C:..\file.xml 的结果,它是相同的。问题是从字节中获取字符串。我尝试了所有可用的编码,但没有任何效果。这是我的代码:
# Add SharePoint snapin if needed
if ((Get-PSSnapin -Name Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null)
{
Add-PSSnapin Microsoft.SharePoint.Powershell
}
...
$splistitem = ...
...
$encode = New-Object System.Text.UTF8Encoding
[xml]$xmlFromSharepoint = $encode.GetString($splistitem.File.OpenBinary()) #throws exception
[xml]$xmlFromFile = get-content C:\....\file.xml #works fine
$web.Dispose()
Write-Host "Press any key to close ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
抛出的异常带有消息:
Cannot convert value "?<?xml version="1.0" encoding="utf-8"?>
..." to type "System.Xml.XmlDocument". Error: "Data at the
root level is invalid. Line 1, position 1."
At C:\aaa.ps1:14 char:24
+ [xml]$xmlFromSharepoint <<<< = $encode.GetString($splistitem.File.OpenBinary
())
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMet
adataException
+ FullyQualifiedErrorId : RuntimeException