You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 19:10:30