PowerShell ISE正常运行的SQL采集脚本在powershell.exe中执行失败
问题原因与解决方案
核心问题
脚本中SqlDataAdapter 对象创建时机错误:初始化$adapter时,$command变量尚未定义(此时$command为$null),导致SqlDataAdapter的SelectCommand属性未正确绑定到后续创建的查询命令。
PowerShell ISE中能正常执行是因为它是交互式会话,可能之前的运行残留了$command变量;而全新的PowerShell进程(如powershell.exe或任务计划)中没有这个残留变量,因此触发错误。
修正后的脚本
# Variables for server, database and query $server = 'dbhost1.local' $database = 'test' $query = "SELECT * FROM ProdDB1" $tempFile ="c:\temp\temp.csv" $ctpmCsv = "C:\temp\Mapping.csv" # Set up the objects needed - 调整创建顺序 $connection = New-Object -TypeName System.Data.SqlClient.SqlConnection $dataset = New-Object -TypeName System.Data.DataSet # Set the connection string (using single sign on) and open the connection $connection.ConnectionString = "Server=$server;Database=$database;Trusted_Connection=True;" $connection.Open() # Create a command object and assign the query $command = $connection.CreateCommand() $command.CommandText = $query # 先创建command,再初始化SqlDataAdapter $adapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter $command # Fill the dataset and count the rows returned at the same time $rowCount = $adapter.Fill($dataset) # Since the dataset is populated we can now close the connection $connection.Close() # Return the results $dataset.Tables.rows | Export-Csv -Path $tempFile -NoTypeInformation (Get-Content -LiteralPath $tempFile | Select-Object -Skip 1) -replace '"', '' | Set-Content -LiteralPath $ctpmCsv
关键修改点
- 将
$adapter的初始化移到$command创建并赋值之后,确保SqlDataAdapter能正确绑定到有效的查询命令。 - 也可以保留原顺序,但在创建
$command后手动添加$adapter.SelectCommand = $command,效果相同。
任务计划执行注意事项
- 确保任务计划的执行账户具备:
- 目标SQL Server的Windows身份验证权限(脚本使用
Trusted_Connection=True) - 对
c:\temp目录的读写权限
- 目标SQL Server的Windows身份验证权限(脚本使用
- 任务的"操作"中,PowerShell命令建议使用:
避免因执行策略限制导致脚本无法运行。powershell.exe -ExecutionPolicy Bypass -File "C:\temp\dbExport.ps1"
内容的提问来源于stack exchange,提问作者Foolishstar
相关产品推荐
相关产品推荐

