【问题标题】:How do you format XML output properly from Powershell using invoke-sqlcmd如何使用 invoke-sqlcmd 从 Powershell 正确格式化 XML 输出
【发布时间】:2020-08-17 18:33:58
【问题描述】:

下面是我的 PowerShell 脚本,它连接到远程 SQL 服务器并将结果存储到 XML 文件中。

$SQLResult = Invoke-Sqlcmd -inputfile $inputfile -ServerInstance $ServerInstance -Database $Database -Username $Username -Password $Password 
$PropertyName = ($SQLResult | Get-Member -MemberType Property | Where {$_.Name -like "XML*"}).Name
$SQLResult.$PropertyName | Out-File -FilePath "C:\Temp\ExportFile.xml" -Force

理想情况下,它应该像这样返回干净整洁的东西(当我在 SQL Server Management Studio 中打开结果时也是如此):

<Text>
    <Data>I am happy</Data>
</Text>

但是,当我打开文件时,它给了我:

<Text><Data>I am happy</Data></Text>

我曾尝试使用Export-Clixml,但返回的 XML 被一些名为 &lt;props&gt; 的无意义标签包围,这不是我的标签之一。

谁能帮我解决这个问题,不知道用哪种方法将其保存为原始格式。

【问题讨论】:

标签: sql xml powershell invoke-sqlcmd


【解决方案1】:

写回磁盘时使用XmlWriter 格式化和缩进它:

# Create settings object, make sure we get the indentation
$writerSettings = [System.Xml.XmlWriterSettings]::new()
$writerSettings.Indent = $true

try{
  # Create the writer
  $writer = [System.Xml.XmlWriter]::Create("C:\Temp\ExportFile.xml", $writerSettings)

  # Convert your XML string to an XmlDocument, 
  # then save the document using the writer
  ([xml]$SQLResult.$PropertyName).Save($writer)
}
finally {
  # discard writer (closes the file handle as well)
  $writer.Dispose()
}

【讨论】:

  • 我试过了,但它返回错误:无法将值“System.Object[]”转换为类型“System.Xml.XmlDocument”。错误:“'>' 是一个意外的标记。预期的标记是 '='。第 3 行,位置 3。”
  • @David 听起来$SQLResult.$PropertyName 解析为的任何字符串值都不是有效的 XML :)
  • 有没有办法查看我的 XML 文件是否有问题:( rly 不知道
  • @David 如果您只是将$SQLResult.$Property 的值打印/输出到屏幕上,那么第 3 行是什么?
  • PS C:\Users\David Kao> $SQLResult.$Property PS C:\Users\David Kao>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-14
  • 1970-01-01
相关资源
最近更新 更多