Search code examples
powershellsqlcmd

Specifying SQL script with multiple statements for sqlcmd in PowerShell


I need to query across multiple (several) databases to see if there is a specific SQL Server Agent Job name on each. I would have thought that SEMICOLON characters would separate SQL statements, but no combination of them seems to work. Am I stuck with specifying `r`n to separate statements? Is there a better way?

@('DBDEV','DBTEST','DBPROD') |
    ForEach-Object {
        & sqlcmd -S $_ -q "SELECT '$_', name FROM msdb.dbo.sysjobs SJ WHERE name = 'THE_JOB_NAME'`r`nGO`r`nEXIT"
    }

Solution

  • A combination of what was mentioned by AdminOfThings and vonPryz:

    $query = @"
    SELECT Name
    FROM msdb.dbo.sysjobs SJ
    WHERE name = 'THE_JOB_NAME'
    "@
    
    $databases = @('DBDEV','DBTEST','DBPROD')
    foreach ($database in $databases) {
        Invoke-SqlCmd -ServerInstance $_ -Database 'msdb' -Query $query
    }