1

I am using a powershell script which will return an XML from a sqlquery of FOR XML EXPLICIT type. Now, the query returned the XML in a column with header and dashed lines

XML 32776498797309
---------------------
<data>asdsafafaf<\data><value>dfsasfasfdfasdf....
dfdsfsdgregrge<\value><value>asdfasdfadfadfsda<\v
alue>

Here, some how we were able to remove header , dashed line and truncating of data. but still the data comes in new line so if we open the XML it throws error because at some places the tag gets distributed as shown above. Basically, new line issue is there. We tried -width 4096 but since XML is huge it is not proper. Please help, stuck big time.

Query used :

 invoke-sqlcmd -inputFile $inputFilePath -serverinstance $dbHostName
                  -database $dbName -username $userName -password $password
                  | Format-Table -hide -Wrap -AutoSize 
                  | Out-File -filePath $outputFilePath -width 4096
Shavez
  • 63
  • 1
  • 13

2 Answers2

2

Try using set-content instead of out-file. Out-file will use the host/console formatting while set-content does not. You'll need to handle outputting XML to string

invoke-sqlcmd ....| select -expandproperty XML | set-content -path $outputFilePath

Edited. Added full working example:

#Contents of my test inputfile.sql:
SELECT CAST ('<EVENT_INSTANCE>
  <EventType>CREATE_TABLE</EventType>
  <PostTime>2011-04-26T15:05:21.333</PostTime>
  <SPID>56</SPID>
  <ServerName>Z001\SQL1</ServerName>
  <LoginName>Contoso\u00</LoginName>
  <UserName>dbo</UserName>
  <DatabaseName>AdventureWorksDW2008R2</DatabaseName>
  <SchemaName>dbo</SchemaName>
  <ObjectName>AdventureWorksDWBuildVersion</ObjectName>
  <ObjectType>TABLE</ObjectType>
  <TSQLCommand>
    <SetOptions ANSI_NULLS="ON" ANSI_NULL_DEFAULT="ON" ANSI_PADDING="ON" QUOTED_IDENTIFIER="ON" ENCRYPTED="FALSE" />
    <CommandText>CREATE TABLE [dbo].[AdventureWorksDWBuildVersion] (
[DBVersion] [nvarchar] (50) NULL,
[VersionDate] [datetime] NULL 
) ON [PRIMARY];
</CommandText>
  </TSQLCommand>
</EVENT_INSTANCE>' AS XML)



$inputFilePath = "C:\Temp\inputfile.sql"
$dbHostName = "$env:computername\sql1"
$outputFilePath = "C:\Temp\output.txt"

#Notice Extra Line Breaks
invoke-sqlcmd -inputFile $inputFilePath -serverinstance $dbHostName | 
    Format-Table -hide -Wrap -AutoSize |
    Out-File -filePath $outputFilePath -width 4096

#No Extra line breaks using set-content
invoke-sqlcmd -inputFile $inputFilePath -serverinstance $dbHostName | select -expandproperty Column1 | set-content -Path $outputFilePath
Chad Miller
  • 40,127
  • 3
  • 30
  • 34
0

Use -MaxCharLength parameter of Invoke-SQLCMD command. By default it 4000. it will truncate big XMLs.

See Invoke-SqlCmd doesn't return long string?

Community
  • 1
  • 1
vitrilo
  • 1,437
  • 16
  • 20