Owl Owl - 3 months ago 13
PowerShell Question

Catch error invalid namespace "root\SecurityCenter2"

Trying to retrieve the list of installed antivirus with on remote computers with below command.

Get-WmiObject -Namespace "root\SecurityCenter2" -Class AntiVirusProduct


computer with antivirus shows installed antivirus details.
But

Invalid namespace “root\SecurityCenter2”


error is thrown if the computer do not have any antivirus trying to catch the error and export csv that computer has no antivirus

catch {
Write-Warning "[ERROR] invalid namespace [$($computer)] : $_"
$noantivirus+=$computer
}
$noantivirus | out-file -FilePath c:\noantivirus.csv -Force


No luck

Answer

That doesn't appear to be a terminating error so it wouldn't be caught in a try catch statement. Try catch statements only catch terminating errors so you will need to tell PowerShell to treat the non-terminating error as a terminating error by using -ErrorAction Stop like this:

try
{
    Get-WmiObject -Namespace "root\SecurityCenter2" -Class AntiVirusProduct -ErrorAction Stop
}
catch
{
    Write-Warning "[ERROR] invalid namespace [$($computer)] : $_"
    $noantivirus+=$computer
}
$noantivirus | out-file -FilePath  c:\noantivirus.csv -Force