我正在嘗試使用腳本塊查詢SQL Server並傳入一組不同的Windows憑據。如果我在與SQL Server相同的機器上運行該腳本,該腳本將正常工作,但當我嘗試遠程運行它時會失敗。我知道我可以遠程訪問SQL服務器,因爲我可以使用SQL Server Managment Studio訪問SQL服務器並手動運行查詢。以下是我正在嘗試使用的代碼。我在腳本中的點之前指定了服務器,數據庫和查詢。PowerShell查詢具有不同Windows憑據的遠程SQL Server
$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
也許我錯過了一些東西。但我不想嘗試啓動遠程會話。我正在PowerShell腳本所在的機器上創建一個新的會話。我正在傳遞一組不同的Windows憑據,而不是我登錄該會話時使用的憑據。如果我刪除腳本塊,只需登錄到具有訪問SQL服務器的Windows憑據的計算機,就可以正常工作。即使我從不同的機器運行腳本比SQL Server。 – seanmt13
會話是遠程還是本地,無關緊要。提供憑證的會話的標準身份驗證不會傳遞用戶名和密碼,因此它們不能用於連接到另一個系統。 –
實際上,憑據在調用Start-Job時會通過。這是使用腳本塊的重點。我可以使用與當前會話不同的憑據進行調用。以下是指向正確方向的鏈接。 [MSDN開始作業](https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/start-job)[與開始作業的SQL連接](http:// arthurremy.com/index.php/108-tips/338-access-sql-server-integrated-security-with-different-windows-credentials-in-powershell) – seanmt13