Powershell - Export SQL to XML to file - no clean output - sql-server

I am trying to export a sql query to an xml file with Powershell using the below script:
$SQLResult = Invoke-Sqlcmd -MaxCharLength ([int]::MaxValue) -AbortOnError -EncryptConnection -ConnectionTimeout $TIMEOUT -Database $Database -ServerInstance $SQL_SERVER_FULLNAME_SOURCE -Username $SQL_ACCOUNT_NAME_SOURCE -Password $SQL_ACCOUNT_PASSWORD_SOURCE -Query $QUERY
$PropertyName = ($SQLResult | Get-Member -MemberType Property | Where {$_.Name -like "XML*"}).Name
$SQLResult.$PropertyName | Out-File -FilePath $OutputFile -Force
It should generate a file like below:
<vendors>
<vendor>
<administration>YIT</administration>
<FISCALCODE>804658055B01</FISCALCODE>
<accountNumber>10001</accountNumber>
<Offset_LedgerAccount></Offset_LedgerAccount>
<name>Comp Europe B.V.</name>
<shortName>Comp Europe B.V.</shortName>
<TAXEXEMPTNUMBER>NL801238055B01</TAXEXEMPTNUMBER>
<DefaultDescription></DefaultDescription>
<invoiceType>Non-PO CEE-FN-ACQ</invoiceType>
<IBAN>NL57MHCB0212303590</IBAN>
<CUSTOMERACCOUNT></CUSTOMERACCOUNT>
<TAXITEMGROUP></TAXITEMGROUP>
<IncludeOrderReference>Unknown</IncludeOrderReference>
<lineText></lineText>
<lines>Unknown</lines>
</vendor>
<vendor>
<administration>YIT</administration>
<FISCALCODE>03840123961</FISCALCODE>
<accountNumber>20001</accountNumber>
<Offset_LedgerAccount></Offset_LedgerAccount>
<name>4ABCD - For Marketing s.r.l.</name>
<shortName>4ABCD-FOR MARKETING</shortName>
<TAXEXEMPTNUMBER>03840123961</TAXEXEMPTNUMBER>
<DefaultDescription></DefaultDescription>
<invoiceType>Purchase invoice</invoiceType>
<IBAN>IT93M0306912330615256048252</IBAN>
<CUSTOMERACCOUNT></CUSTOMERACCOUNT>
<TAXITEMGROUP></TAXITEMGROUP>
<IncludeOrderReference>Unknown</IncludeOrderReference>
<lineText></lineText>
<lines>Unknown</lines>
</vendor>
<vendors>
In real it can contain a few thousand records.
The problem with the various other options that I used is that the output file is either truncated, or it contains double quotes. With the above script suddenly extra spaces are added that are repeated every certain block of output. If I run the query in MSMS it generates a perfectly clean result that I can save as .xml file.
<vendor>
<administration>YIT</administration>
<FISCALCODE>0381230961</FISCALCODE>
<accountNumber>20001</accountNumber>
<Offset_LedgerAccount/>
<name>4ABCD - For Marketing s.r.l.</name>
<shortName>4ABCD-FOR MARKETING</shortName>
<TAXEXEMPTNUMBER>03840123961</TAXEXEMPTNUMBER>
<DefaultDescription/>
<invoiceType>Purchase invoice</invoiceType>
<IBAN>IT93M03069121238252</IBAN>
<CUST OMERACCOUNT>< CUSTOMERACCOUNT><TAXITEMGROUP>< TAXITEMGROUP><IncludeOrderReference>Unknown< IncludeOrderReference><lineText>< lineText>
As you can see above it starts okay but then suddenly it starts adding a single space to certain nodes, not to all. Then it continues okay for some records and then a gain a line with a single space in some of the nodes.
I tried various solutions but none of them seem to work for me. Can somebody explain what I am doing wrong? The actual query I use is below.
SELECT
v.[DATAAREAID] AS [administration]
,v.[FISCALCODE]
,v.[VENDORACCOUNTNUMBER] AS [accountNumber]
,v.[DEFAULTOFFSETLEDGERACCOUNTDISPLAYVALUE] AS [Offset_LedgerAccount]
,v.[VENDORORGANIZATIONNAME] AS [name]
,v.[VENDORSEARCHNAME] AS [shortName]
,CASE WHEN LEFT(v.[TAXEXEMPTNUMBER],2)='IT' THEN RIGHT(v.[TAXEXEMPTNUMBER],LEN(v.[TAXEXEMPTNUMBER])-2) ELSE v.[TAXEXEMPTNUMBER] END AS [TAXEXEMPTNUMBER]
,ISNULL(v.[NOTES],'') AS [DefaultDescription]
,ISNULL(ipvp.[INVOICETYPENAME],'') AS [invoiceType]
,ISNULL(vba.[IBAN],'') AS [IBAN]
,ISNULL(c.[CUSTOMERACCOUNT],'') AS [CUSTOMERACCOUNT]
,ISNULL(itc.[TAXITEMGROUP],'') AS [TAXITEMGROUP]
,'Unknown' AS [IncludeOrderReference]
,v.[DESTINATIONCODE] AS [lineText]
,'Unknown' AS [lines]
FROM [dbo].[RetailVendVendorV3Staging] v
LEFT OUTER JOIN [dbo].[AXTip_ParametersVendTableStaging] ipvp ON v.[VENDORACCOUNTNUMBER]=ipvp.[VENDORACCOUNT] AND v.[DATAAREAID]=ipvp.[DATAAREAID]
LEFT OUTER JOIN [dbo].[VendVendorBankAccountStaging] vba ON vba.[DATAAREAID]=v.[DATAAREAID] AND vba.[VENDORACCOUNTNUMBER]=v.[VENDORACCOUNTNUMBER] AND vba.[VENDORBANKACCOUNTID]=v.[BANKACCOUNTID]
LEFT OUTER JOIN [dbo].[CustCustomerV3Staging] c ON c.[VENDORACCOUNT]=v.[VENDORACCOUNTNUMBER] AND v.[DATAAREAID]=c.[DATAAREAID]
LEFT OUTER JOIN [dbo].[AXTip_ImportTaxcodeStaging] itc ON itc.[ACCOUNTRELATION]=v.[VENDORACCOUNTNUMBER] AND itc.[DATAAREAID]=v.[DATAAREAID] AND itc.[EXTERNALTAXCODE]='I'
WHERE v.[DATAAREAID] ='YIT' AND v.[FISCALCODE]!=''
FOR XML PATH('vendor'), root('vendors')

I read quite a lot of issues using the method that I used in the opening post. The method described in the link below seems a more "powershell" way to generate an xml file using sql-data. I copied this method and it works well.
stuartsplace.com: powershell-and-sql-server-exporting-data-xml

Related

Capturing logs for .sql statements though powershell

I'm trying to figure out a good way to run insert/select/update statements into a MSSQL database through PowerShell scripting and log it thoroughly. I have managed to use Invoke-Sqlcmd which does the inserts and select statements pretty fine. But my concern is to capture the logs some where as an output file. That is when doing inserts the log should capture the no. of rows affected/inserted with the data that was inserted.
Invoke-Sqlcmd used:
PS C:\Users\moshink\Desktop\Powershell SQL> Invoke-Sqlcmd -Server $server -Database $db -Username $user -Password $pass -InputFile ".\test.sql" | Out-File -FilePath ".\test_$datetime.rpt" >> $LogFile
test.sql file query below:
use TCS_MIS
select * from tblMasterAccountType where acctType in ('0121') and intCat in ('0020')
--insert into tblMasterAccountType values ('DEP','0121','0020','PARENTHOOD ASSISTANCE ACCOUNT')
the test.sql file is called in the Invoke-Sqlcmd.
This file can be dynamic with any query going in there.
The Out-File ".\test_$datetime.rpt" does capture the select statement outputs if the data exits matching the criteria, but it will be blank if no data.
Is there something that can be ran to capture instantly when running a Insert .sql file/script? i.e. which will say 20 rows inserted and listing out the data inserted.
Basically what I'm after is a thorough logging when running any .sql scripts through PowerShell. It should capture no of rows affected with the data inserted/updated/deleted and the user who performed it.

How to use result output columns as objects in MSSQL

What I'm trying to achieve is finding out how long retention a database backup has by using DATEDIFF function.
But in order to use DATEDIFF I would need something to compare, the data from the result, because I don't know it being anywhere else.
Why from a result ?
I found out that this command gives me all the info I need to accomplish my task (BackupFinishDate, ExpirationDate):
RESTORE HEADERONLY FROM DISK = 'X:\Backups\Backuptest.bak'
I'm pretty sure I'm not allowed to create temp tables in production servers, so if this is one option, I'm afraid I can't use that.
PS! If there's a better way to find out retentiondays of a backup, I'd happily use that. If this would be possible in PowerShell, that would be even better.
Well, it seemed I answered my own question with the PowerShell hint.. I gave myself :P
Solution was:
$bkp_start = Invoke-Sqlcmd -ServerInstance myServer -Query "RESTORE HEADERONLY FROM DISK = 'X:\Backups\Backuptest.bak'" | Select-Object -ExpandProperty BackupFinishDate
$bkp_end = Invoke-Sqlcmd -ServerInstance myServer -Query "RESTORE HEADERONLY FROM DISK = 'X:\Backups\Backuptest.bak'" | Select-Object -ExpandProperty ExpirationDate
$RetentionInDays = New-TimeSpan -Start $bkp_start -End $bkp_end | Select-Object -ExpandProperty Days
Write-Output "Retention period : $RetentionInDays"
I love PowerShell.. looks a bit clunky, but it works and I don't know a better way at this time.

Powershell Invoke-Sqlcmd - return multiple datasets

I'm looking for suggestions on either returning multiple datasets, or keeping the session open, with Invoke-SqlCmd?
I have a series of SQL queries that use temporary tables to generate a few related views of the data that I am sending on (via Excel) to a manager. As we work on what is required from the datasets, I am getting a little tired of cutting and pasting samples into Excel.
I thought to use Powershell to simply send the results to HTML files as output for the manager, however I ran into a couple of problems
If I put the final extracts into one SQL file, Powershell appends all of the data into a single result set (sort of a union of the tables)
If I attempt to build the temporary tables and then extract each query individually, each Invoke-Sqlcmd is a seperate session, meaning my Temporary tables get dropped.
I'm looking for suggestions on either returning multiple datasets, or keeping the session open?
Invoke-Sqlcmd -InputFile .\GenerateTimecard.sql -Variable $params | Out-Null;
#{
'Summary' = 'select * from #WeeklyTimeSummary;'
'ByDay' = 'select * from #WeeklyTimeDaily order by postdate desc;'
'ByTask' = 'select * from #WeeklyTimeEvents order by HoursSpent desc;'
'Detail' = 'select * from #WeeklyTimeDetail order by postdate desc;'
}.GetEnumerator() | ForEach-Object {
Write-Output $_.Name;
$fname = $_.Name + '.html';
Invoke-Sqlcmd -Query $_.Value | ConvertTo-Html | Out-File -Encoding ascii $fname;
};
The Description section from Get-Help Invoke-Sqlcmd says it supports GO commands so you could try running everything at once. Personally I'd use the -InputFile parameter and pipe the results to Out-File.
You can specify the ApplicationName parameter for Invoke-SqlCmd, which results in a different SQL connection.
Omitting ApplicationName will result in the temp tables getting removed the second time you call Invoke-SqlCmd.
Something like:
Invoke-SqlCmd -ApplicationName CreateTable -Query 'CREATE TABLE ##FooTable (FooKey INT)
Invoke-SqlCmd -ApplicationName SelectTable -Query 'SELECT * FROM ##FooTable'

How to stop truncating of data when outputting XML from ReportServer using data returned from a stored procedure with Powershell (large XML file)

I have been twiddling with a fairly simple idea to export ReportServer reports from the underlying database and then find its dependent stored procedures and export them as well.
However, when testing initially I found that the XML data for the report itself is truncated in the standard way I export things to files, and I think I may be using an incorrect method.
The code is fairly simple at this point, and I am using a simplified report called "ChartReport":
Import-Module 'sqlps'
$saveloc = "$home\savedata\filename.txt"
$dataquery = #"
DECLARE #name NVARCHAR(MAX)='ChartReport',
#path NVARCHAR(MAX) = '/ChartReport'
SELECT CAST(CAST(c.Content AS VARBINARY(MAX)) AS XML) [ReportData], c.Name, c.Path
FROM ReportServer.dbo.Catalog c
WHERE c.Name = #name
AND c.Path LIKE #path+'%'
"#
Invoke-SQLCMD -Query $dataquery | select ReportData | Out-File $saveloc
I have verified the query returns XML (The underlying XML file itself is over 25000 characters, and I would be happy to provide a link to it if anyone is interested), however when I save the file I get something like:
Column1
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns:cl="http://schemas.microsof...
I have attempted to use some of the ideas already posted on SO, such as:
> $somefile Powershell 2: Easy way to direct every bit of output to a file?
out-file and specifying width Powershell Add-Content Truncating Output
Using the format-table with -autosize and -wrap
Each of these fail at some point (though the format-table method gets pretty far before it truncates).
I would definitely consider some sort of XML specific solution, but really I think it is just that I am missing some information. As far as I am considering, this is a file of "stuff" and I want to write said file to the disk after it is loaded into the object.
Would iterating over some sort of line break and writing each line of the object to a file be the idiomatic answer?
Use -MaxCharLength parameter of Invoke-SQLCMD command. By default it 4000.
See Invoke-SqlCmd doesn't return long string?

Pass a powershell variable into a SQL value during out-datatable (invoke-sqlcmd2)

I want to insert a PowerShell variable value with a Select as I build a datatable from a SQL query.
Borrowed function invoke-sqlcmd2 from TechNet gallery and dot-sourced it in.
$NewSequenceID = invoke-sqlcmd2 -ServerInstance "MyServer" -Database "MyDB" -Query "INSERT INTO [Sequence] (TimeStarted) SELECT GETDATE(); SELECT max(SequenceID) as SequenceID FROM [Sequence]" | foreach { $_.SequenceID }
This generates a new sequence ID and stamps the time we started the batch. Results in a single number which will identify this run. Verified with 'write $NewSequenceID'.
I want to keep later results from queries together with this SequenceID for analysis.
Then I have this:
$PollTime = Get-Date -format "yyyy-MM-dd HH:mm:ss"
Then I want to do this: (Edit: This statement is not working - error message at the bottom)
$AuditUserOutput = invoke-sqlcmd2 -ServerInstance "MyServer2" -Database "MyDB2" -Query "SELECT $NewSequenceID, $PollTime, [USERID], [PID], [UDATE] FROM [MyTable]" -As 'Datatable'
And do some things with the table, then write it after with write-datatable.
If I select NULL for the first two values and grab the other three from the existing table, it works fine. I want to add the $NewSequenceID and $PollTime from the previous statements.
I've read a dozen pages about using ` (backtick), $, {}, and on and on, but I haven't gotten it right. Can someone help with the correct syntax for inserting these variable values into the selection?
PS Error is: Exception calling "Fill" with "1" argument(s): "Invalid pseudocolumn "$NewSequenceID"."
You're interpolating the variables correctly in PowerShell. If I'm understanding this correctly, the problem is with your SQL query. I'm going to make an inference here, but I think this is probably what you want:
$AuditUserOutput = invoke-sqlcmd2 -ServerInstance "MyServer2" -Database "MyDB2" -Query "SELECT [NewSequenceID], [PollTime], [USERID], [PID], [UDATE] FROM [MyTable] WHERE NewSequenceID = '$NewSequenceID' AND PollTime = '$PollTime'" -As 'Datatable'
If not, please clarify by responding to the questions above.
I was able to work around this by first creating a variable to store the query text, which allowed for the natural substitution I needed:
$AuditUserQuery = "SELECT '$NewSequenceID', '$PollTime', [USERID], [PID], [UDATE] FROM [AUDITUSER]"
Then calling that variable as the $query when building the datatable.
This avoided the parameterization problem experienced before.

Resources