Below is a PowerShell function I wrote as part of a larger script for collating useage statistics from a SaaS environment where it is impractial to know if the database in question will or won’t be one which contains the data needed. By querying the table schema and returning true/false as the output, it allows for its output to be used in an If condition for whether to proceed with running the subsequent queries.
$Query = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'$TableName'"
$OutputIsDataTable = Invoke-Sqlcmd2 -ServerInstance $Instance -Database $Database -Query $Query
$Return = $true
$Return = $false
The inspiration for this came from this post although it takes a longer approach which has to do a lot of error handling due to the approach used.
Senior consultant and company director at The Full Circle. Passionate about automation scripting, end user experience and cloud technology.