I\'m trying to execute the Invoke-Sqlcmd
command (from the SqlServer module) to run a query as a different AD user. I know there\'s the -Credential
For those interested, below is the code I implemented. Depending on whether or not $credential
is passed, Invoke-Sqlcmd
will either run directly, or using a background job.
I had to use -As DataTables
instead of -As DataSet
, as the latter seems to have issues with serialisation/deserialisation (see accepted answer for more info).
function Exec-SQL($server, $database, $query, $credential) {
$sqlData = @()
$scriptBlock = {
Param($params)
Import-Module SqlServer
return Invoke-Sqlcmd -ServerInstance $params.server -Database $params.database -query $params.query -As DataTables -OutputSqlErrors $true
}
if ($PSBoundParameters.ContainsKey("credential")) {
$job = Start-Job -ScriptBlock $scriptBlock -Credential $credential -ArgumentList $PSBoundParameters
$sqlData = Receive-Job -Job $job -Wait -AutoRemoveJob
} else {
$sqlData = & $scriptBlock -params $PSBoundParameters
}
return $sqlData
}