Powershell convertto-csv~只有在Invoke-Sqlcmd没有返回结果时才打印标题? [英] Powershell convertto-csv ~ How do you print headers only when no results returned from Invoke-Sqlcmd?

查看:80
本文介绍了Powershell convertto-csv~只有在Invoke-Sqlcmd没有返回结果时才打印标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行SQL查询并将结果导出到CSV文件的PowerShell脚本。问题是当查询未返回任何结果时,后续CSV文件为空。我希望它只打印标题行。我怎样才能做到这一点?这里
是我的代码:


Invoke-Sqlcmd -ServerInstance'(local)'  -Database MyDatabase -MaxCharLength 50000 -Query $ SQLQuery | convertto-csv -Delimiter'|' - NoTypeInformation | %{$ _ -replace'" |"',''} | %{$ _ -replace" ^`"",''} | %{$ _ -replace
"`" $",''} | out-file $ FilePathName -fo -en ascii

解决方案

添加UNION All添加一行到您的选择查询并在导出后删除最后一行。


示例:

 


< blockquote> q = @"

SELECT [CustomerID],[CompanyName]
FROM [Northwind]。[dbo]。[Customers]
- 其中CustomerID ='XXXXXX'
UNION ALL
选择''CustomerID','CompanyName


" @
Invoke-SQLCmd -ServerInstance


svr.Name -database

I have a PowerShell script that is running a SQL query and exporting the results to a CSV file. The problem is that when the query returns no results, the subsequent CSV file is blank. I would like it to just print the header row. How can I do that? Here is my code:

Invoke-Sqlcmd -ServerInstance '(local)'  -Database MyDatabase -MaxCharLength 50000 -Query $SQLQuery | convertto-csv -Delimiter '|' -NoTypeInformation | % { $_ -replace '"|"', ''} | % { $_ -replace "^`"",''} | % { $_ -replace "`"$",''} | out-file $FilePathName -fo -en ascii

解决方案

Add UNION All to add a row to your select query and remove the last row after export.

An example:


q = @" SELECT [CustomerID],[CompanyName] FROM [Northwind].[dbo].[Customers] -- where CustomerID='XXXXXX' UNION ALL Select '' CustomerID, ''CompanyName "@ Invoke-SQLCmd -ServerInstance


svr.Name -Database


这篇关于Powershell convertto-csv~只有在Invoke-Sqlcmd没有返回结果时才打印标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆