スクリプト ブロックを使用して SQL Server にクエリを実行し、別の Windows 資格情報セットを渡そうとしています。スクリプトは、SQL Server と同じマシンで実行すると機能しますが、リモートで実行しようとすると失敗します。SQL Server Managment Studio を使用して SQL サーバーにアクセスし、クエリを手動で実行できるため、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