r/PowerShell • • Dec 20 '22

Solved SNMP query

Hi all, I am trying to use SNMP to query status of a UPS using the code in a #SCOM monitor.

If I run the code from PS ISE it works fine, but when it's run by the SCOM agent, I have this error:

Failed to open SNMP session

This is the code I use:

try

{

$SNMP = New-Object -ComObject olePrn.OleSNMP

}

catch

{

Write-Debug "Error creating SNMP object"

"Error creating SNMP object - $($_.Exception.Message)" | out-file -FilePath "C:\temp\upsonbatt.log" -append

exit

}

try

{

$UPSIPAddress = [System.Net.Dns]::GetHostAddresses($UpsName).IPAddressToString

$SNMP.open($UPSIPAddress, "public", 2, 3000)

}

catch

{

Write-Debug "Error opening SNMP connection"

"SNMPERR opening $UpsName with IP $UPSIPAddress - $($_.Exception.Message)" | out-file -FilePath "C:\temp\upsonbatt.log" -append

exit

}

Someone knows what the last 2 parameters in this command mean ?

$SNMP.open($UPSIPAddress, "public", 2, 3000)

I mean the 2 and the 3000

I cannot find anything on the web, or maybe I cannot find what to look for ;)

Thanks in advance

4 Upvotes

32 comments sorted by

View all comments

Show parent comment

2

u/dragoncuddler Dec 21 '22

Just a quick example outside of SNMP to show how you can test a script outside of SCOM but using the SCOM agent.

  1. Create a powershell script such as
    $Path = 'C:\Temp\verbs.txt'
    $ScomAPI = New-Object -comObject "MOM.ScriptAPI"
    $PropertyBag = $ScomAPI.CreatePropertyBag()
    $FileExists = Get-Item -Path $Path
    If ($FileExists)
    {
    $Message = "$Path Exists"
    }
    Else
    {
    $Message = "$Path Doesn't Exist"
    }
    $PropertyBag.AddValue("MessageText",$Message)
    $SCOMapi.Return($Propertybag)
  2. Run it from a PowerShell prompt
    PS C:\temp> .\SCOMTestFile.ps1
  3. View the output

<DataItem type="System.PropertyBagData" time="2022-12-21T09:09:23.1643455+00:00" sourceHealthServiceId="2370F961-B988-C7C6-EA02-23E07B8852DE"><Property Name="MessageText" VariantType="8">C:\Temp\verbs.txt Exists</Property></DataItem>

OR

<DataItem type="System.PropertyBagData" time="2022-12-21T09:12:45.3514104+00:00" sourceHealthServiceId="2370F961-B988-C7C6-EA02-23E07B8852DE"><Property Name="MessageText" VariantType="8">C:\Temp\verbss.txt Doesn't Exist</Property></DataItem>

1

u/Kiddo_Ogami Dec 21 '22

Very useful. Thanks ;)

1

u/Kiddo_Ogami Dec 21 '22

I tried but had this error:

The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))At line:14 char:1+ $SCOMapi.Return($Propertybag)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : OperationStopped: (:) [], COMException    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

The object $SCOMapi was created successfully however :O