Test if a SQL table exists with PowerShell

Use Case

Occasionally when managing large numbers of SQL Instances and thousands of databases, you have to do some checks prior to running a query against them. One of the ways of ensuring you’re querying the right sort of database is checking if a specific table exists.

This function checks if a table exists by checking the database schema. I’ve seen other functions which query the table itself and check if the result is or isn’t null but this seems more elegant.


function Test-SQLTableExists
{
param ($Instance,$Database,$TableName)
$Return = $SQL = $dataTable = $null
$sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'$TableName'"
$dataTable = Invoke-Sqlcmd2 -ServerInstance $Instance -Database $Database -Query $sql
if ($dataTable) {$return = $true}
else {$return = $false}
$Return
}