我正在尝试使用脚本块查询 SQL Server 并传入一组不同的 Windows 凭据。如果我在与 SQL Server 相同的机器上运行该脚本,但当我尝试远程运行它时失败。我知道我可以远程访问 SQL 服务器,因为我可以使用 SQL Server Managment Studio 访问 SQL 服务器并手动运行查询。下面是我尝试使用的代码。我在脚本中的点之前指定服务器、数据库和查询。
$credentials = Get-Credentials
#Script block
$sqlscript = {
#SQL variables
$sqlDataSource = $sqlServer
$sqlDatabase = $database
$connectionString = "Server="+$sqlDataSource+";Database="+$sqlDatabase+";Integrated Security=SSPI;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = New-Object System.Data.SqlClient.SqlCommand($queryString,$connection)
$command.CommandTimeout=$queryTimeout
# use dataset to get sql results
$dataset=New-Object system.Data.DataSet
$dataAdapter=New-Object system.Data.SqlClient.SqlDataAdapter($command)
[void]$dataAdapter.fill($dataset)
$connection.close()
# dataset has separate results tables
#$versionData = $dataset.Tables[0] #Version query results #not needed
$hardwareData = $dataset.Tables[1] #Hardware query results
$softwareData = $dataset.Tables[2] #Software query results
}
start-job -ScriptBlock $sqlscript -Credential $credentials
# output to separate CSV files
#$versionData | Export-CSV $outputPath -notype #not needed
$hardwareData | Export-CSV $outputPathHardware -notype
$softwareData | Export-CSV $outputPathSoftware -notype