Invoke-Sqlcmd Join variable as table

Invoke-Sqlcmd Join variable as table

有没有办法在 Invoke-Sqlcmd 中将 link 一个 PS 变量作为 table? 我试过了 LEFT JOIN $psvar as p on T1.ID=P.ID

我根据@Cpt.Whale的建议制作了一个 DataTable 更新了脚本。

# Define DataTable Columns
$tbl = New-Object system.Data.DataTable 'tbl_New'
$newcol = New-Object system.Data.DataColumn emplID,([string]); $tbl.columns.add($newcol)
$newcol = New-Object system.Data.DataColumn adGrp,([string]); $tbl.columns.add($newcol)

# Add data from Excel
$exelWkbk = '.\table.xlsx'
$excelQuery = '
        SELECT  F1 as emplID
                ,F2 as pcType
        FROM    [Sheet1$]
'
$queryOutput = Invoke-ExcelQuery $exelWkbk $excelQuery | Select-Object -Skip 1

$queryOutput | ForEach-Object {
    $row = $tbl.NewRow()
    $row.tmplID = ($_.emplID)
    $row.adGrp = ($_.pcType)
    $tbl.Rows.Add($row)
}

# Query SQL Data source joining Excel data
$sqlQuery = "
        USE SQLDATABASE;
        DECLARE @today as date = GETDATE();
        SELECT  emp.USER_ID
                ,wt.HOST
                ,a.pcType as DevicModel
        FROM    workstationTable as wt
                JOIN employeeTable as emp on wt.USER_ID = emp.USER_ID
                JOIN $tbl as a on emp.USER_ID = a.emplID
        WHERE   emp.NAME is not NULL
"
Invoke-Sqlcmd -Query $sqlQuery -ServerInstance 'dbName' |
Out-GridView

Powershell 没有用于对不同数据集进行 SQL 式连接的内置函数。您可以使用 Select-Object 计算属性进行简单查找 - table 类型的东西,但我更喜欢使用基于 LINQ 构建的 Join-Object 模块:

# Gather both data sources into separate list variables:
$sqlData = Invoke-Sqlcmd -ServerInstance 'dbName' -Query '
  USE SQLDATABASE;
    DECLARE @today as date = GETDATE();
    SELECT  emp.USER_ID,wt.HOST
    FROM    workstationTable as wt
      JOIN  employeeTable as emp on wt.USER_ID = emp.USER_ID
    WHERE   emp.NAME is not NULL'
$excelData = Invoke-ExcelQuery $exelWkbk $excelQuery | Select-Object -Skip 1

# join the lists on a specific property
$joined = Join-Object -Type AllInLeft `
    -Left $sqlData    -LeftJoinProperty  USER_ID `
    -Right $excelData -RightJoinProperty EmplID 

$joined | Out-GridView

或者由于您已经在使用 Excel,文件中的 SQL 数据连接可能是一个选项。