I have a script that gets SQL Server properties using SMO. I have the script display the properties out in html but I am having trouble setting it up so that the script still enters a datarow even when the SMO object returns empty because of a connection or other error. How would I get it to enter a string into the data row if the SMO object returns empty or null?
I have already tried an If statement where $serverObject -eq $null and that didn't print it out.
foreach($instance in $instanceList)
{
$serverObject = New-Object Microsoft.SqlServer.Management.Smo.Server($instance)
$instance = $instance.toupper()
$serverName = $serverObject.ComputerNamePhysicalNetBIOS;
$instanceName = $serverObject.InstanceName;
$versionBuild = $serverObject.Information.ResourceVersion;
$servicePack = $serverObject.Information.ProductLevel;
$color = $redColor;
if($serverName -eq $null -and $instanceName -eq $null)
{
[string]$serverName = "Error Connecting"
$instanceName = $instance
}
else
{
if($instanceName -eq $null -and $versionBuild -eq $null)
{
[string]$instanceName = $instance
[string]$versionBuild = "Error"
}
}
}
# Set background color to green if service pack is 2008r2 SP2
if($versionBuild -match $vs2008r2sp2)
{
$color = $greenColor
}
else
{
# Set background color to yellow if service pack is 2008 SP3
if($versionBuild -match $vs2008sp3)
{
$color = $yellowColor
}
else
{
# Set background color to orange if service pack is 2005 SP4
if($versionBuild -match $vs2005sp4)
{
$color = $orangeColor
}
}
}
# Create table data rows
$dataRow = "
<tr>
<td width='10%'>$serverName</td>
<td width='15%'>$instanceName</td>
<td width='5%' bgcolor=`'$color`' align='center'>$versionBuild</td>
<td width='10%' align='center'>$servicePack</td>
</tr>
"
# If statement needed to remove label that were null
If ($versionBuild -ne 'NaN')
{
Add-Content $servicePackReport $dataRow;
Write-Host -ForegroundColor DarkYellow "$serverName $instanceName service pack build = $versionBuild";
$i++
}
}