Unexpected variable type returned by Receive-Job

前端 未结 3 1895
悲哀的现实
悲哀的现实 2020-11-30 15:18

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

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 16:11

    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
    }
    

提交回复
热议问题