Suppress error messages for WMI classes

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Richard Siddaway Richard Siddaway 1 year, 10 months ago.

  • Author
    Posts
  • #22131
    Profile photo of
    Anonymous

    Hi All,
    End user of my script may have two accounts [Exchange(User_ex) and Lync(User_sup)]. When he configured his local PS profile only for exchange (user_ex) and trying to get logical disk info of Lync server(which needs User_sup) then my script suppress error messages for WMI classes, especially for AccessDenied errors.

    I tried by setting the global PS profile variable $ErrorActionPreference=”SilentlyContinue” which was worked but I don't want to use this as this is not a best practice of coding.

    ***Both Exchange and Lync are in the same domain***

    ****

    PS C:\> Get-WmiObject -Class Win32_LogicalDisk -ComputerName hzwas251 -ErrorVariable Err -ErrorAction "SilentlyContinue"

    Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
    At line:1 char:14
    + Get-WmiObject <<<< -Class Win32_LogicalDisk -ComputerName hzwas251 -ErrorVariable Err -ErrorAction "SilentlyContinue" + CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

  • #22139
    Profile photo of GJ
    GJ
    Participant

    Hi,

    You should use try catch block to catch the errors and handle it as you wish. Go through the free ebook "The Big Book of PowerShell Error Handling" available under https://powershell.org/ebooks/ which was written by Dave Wyatt. It's a great resource to understand the error handling.

    This may be the solution for your problem described here.

    
    try
    {
        Get-WmiObject -Class Win32_LogicalDisk -ComputerName hzwas251 -ErrorVariable Err -ErrorAction Stop
    }
    catch
    {
       write-output "Access denied for User_ex"
    }
    
  • #22188
    Profile photo of Richard Siddaway
    Richard Siddaway
    Moderator

    Be aware that other errors can occur, for instance you may not be able to make a DCOM connection to a remote connection, and if you have a generic catch you'll get the access denied message even if that isn't the error. Either have multiple catch statements OR pass the specific error as part of the message output from the catch

You must be logged in to reply to this topic.