How to check whether a site collection does exist via PowerShell using 'ErrorAction'?
The Get-SPSite cmdlet as described here returns either a single site that matches the 'Identity' parameter, or all the sites that match the 'Filter' Parameter. But how can I check whether a specific Site Collection does exist?
The call
Get-SPSite https://win-ppdptgfeo66/sites/MockUp
returns the SPSite object [1] when the SC exist - wonderful.
But when I call it for non-existing site collections I am getting the following error is returned [2].
OK - so this might be the right time to make use of a 'try-catch block' as shown in the following figure.
try {
Get-SPSite https://win-ppdptgfeo66/sites/MockUp
} catch [Exception]
{
Write-Host "Keep calm, the site collection has not been found"
}
As shown in the screenshot below an error occurs and not the expected Information is shown.
But NO, it seems that the try-catch block is not working here.
The solution for checking the existence of a site collection lies in the standard common PowerShell Parameter 'ErrorAction'.
if ([bool] (Get-SPSite https://win-ppdptgfeo66/sites/Mochup -ErrorAction SilentlyContinue) -eq $false) {
Write-Host "Keep calm, the site collection has not been found"
} else {
Write-Host "Wow - Site Collection does exist"
}