使用PowerShell从SQL查询数据时,如何去除开头的行数仅显示数据?
解决PowerShell查询SQL后输出开头行数的问题
问题原因
SqlDataAdapter.Fill()方法会返回填充到DataTable的行数,PowerShell默认会把函数中所有未被显式抑制的输出都打印出来,所以这个行数就被显示在了结果开头。
解决方法
只需要捕获Fill()方法的返回值,不让它输出到控制台即可,修改代码中的对应行:
原代码:
$dap.Fill($dt);
修改为以下任意一种方式:
- 用
$null接收返回值:
$null = $dap.Fill($dt);
- 赋值给一个临时变量(无需使用该变量):
$rowCount = $dap.Fill($dt);
这样就不会把行数输出到控制台,只会显示foreach循环里通过Write-Host输出的ORG_UNIT数据。
修改后的完整脚本示例
Function ProcessSQLServerDataBU_ROLLUP([string]$DBServer, [string]$DBName, [string]$Query) { try { $conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=True;Initial Catalog=$DBName") $conn.Open(); $query = $Query $dap = new-object System.Data.SqlClient.SqlDataAdapter($query,$conn); $dt = new-object System.Data.DataTable; $null = $dap.Fill($dt); # 捕获Fill方法的返回值,避免输出行数 foreach($r in $dt.Rows) { Write-Host $r["ORG_UNIT"] } $conn.Close(); } catch { #Write error message on screen and to a LOG file write-host $_.Exception.Message $_.Exception.Message >> "d:\error.log" } finally { $ErrorActionPreference = "Continue" } } ProcessSQLServerDataBU_ROLLUP "(localdb)\ProjectsV13" "Flavors_DevEx" "SELECT [ORG_UNIT] FROM [BU_ROLLUP]"
内容的提问来源于stack exchange,提问作者John John
相关产品推荐
相关产品推荐

