I slightly modified the catch block to display the exception.
catch [Exception]
{
Write-Host "$_.Exception.GetType().FullName, $_.Exception.Message" -ForegroundColor Red
}
}
Then as suspected it was throwing below runtime error
New-Object : Cannot find type [Microsoft.SqlServer.Management.SMO.Server]: make sure
the assembly containing this type is loaded.
I fixed it by using below command
Add-Type -Path 'C:\Program Files\Microsoft SQL Server\120\SDK\Assemblies\Microsoft.SqlServer.Smo.dll'
Next it was throwing below error message :
You cannot call a method on a null-valued expression..Exception.GetType().FullName, You cannot
call a method on a null-valued expression..Exception.Message