What is this?

This knowledgebase contains questions and answers about PRTG Network Monitor and network monitoring in general.

Learn more

PRTG Network Monitor

Intuitive to Use. Easy to manage.
More than 500,000 users rely on Paessler PRTG every day. Find out how you can reduce cost, increase QoS and ease planning, as well.

Free Download

Top Tags


View all Tags

Powershell Interface for PRTG API

Votes:

15

I am not really sure where I should post this, as its not a question, its just sharing something that I have been working on:

I have put together a Powershell module so I can manage my PRTG setup.

It allows me to quickly do the following: 1, update massive groups of devices with additional sensors. 2, import devices from CSV and assigned to group 3, report on all sensors that are in a certain state (useful for a daily overall status email)

There are examples in the code.

I am certainly no Powershell Guru, In fact this is the first thing I have written in Powershell.

######ignore invalid SSL Certs##########
add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

######setup details, access related.
#$auth = "username=prtgadmin&passhash=618951066"
$auth = "username=api_access&passhash=1982551677"
$PRTGHost = "10.254.199.20"



##############################################
############Get-prtgSensorInGroup###########
##############################################
# will return ALL sensors listed in PRTG, for a given Group (via its ID) (limited to 2500)
#default is the root (ID=0)
#its important to remember that a "Group" is also a device, and probe etc.
#eg
#Get-prtgSensorInGroup 8011

function Get-prtgSensorInGroup([string]$StartingID=0)
{
    $url = "https://$PRTGHost/api/table.xml?content=sensors&output=csvtable&columns=objid,probe,group,device,sensor,status,message,lastvalue,priority,favorite,tags&id=$StartingID&count=2500&$auth"
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore

    convertFrom-csv $request
} # end function




##############################################
############Get-prtgDevicesInGroup####################
##############################################
# will return ALL Devices listed in PRTG, for a given Group (via its ID) (limited to 2500)
#default is the root (ID=0)
#if you want to find 1 device(ID=8011), then use: Get-prtgDevicesInGroup | where {$_.ID -eq 8011}
#anther example, seaching for an IP
#Get-prtgDevicesInGroup | where {$_.host -eq "10.81.8.36"}

#you may also want to return many devices, eg
#Get-prtgDevicesInGroup | where {$_.host -like "10.81.8.*"}

function Get-prtgDevicesInGroup ([string]$StartingID=0)
{
    #if ($script:devicesCached -eq $false){
        $url = "https://$PRTGHost/api/table.xml?content=devices&output=csvtable&columns=objid,probe,groupid,device,host,downsens,partialdownsens,downacksens,upsens,warnsens,pausedsens,unusualsens,undefinedsens,comments&id=$StartingID&count=2500&$auth"
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
        $getprtgDeviceRet = convertFrom-csv ($request)
        $getprtgDeviceRet 
    #    write-host "got devices from website..."
    #    $script:devicesCached = $true
    #}else{
    #    write-host "got groups from cache..."
    #    $getprtgDeviceRet 
    #}
} # end function


##############################################
############Get-prtgGroupsInGroup####################
##############################################
# will return ALL Groups listed in PRTG, for a given Group (via its ID) (limited to 2500)
#default is the root (ID=0)

#will will list all the group recurively under the listed group (ie, not JUST the children)

#eg, return al lthe groups in the local probe
# get-prtgGroupsInGroup 1

function get-prtgGroupsInGroup ([string]$StartingID=0)
{
   
    $url = "https://$PRTGHost/api/table.xml?content=groups&output=csvtable&columns=objid,probe,group,name,downsens,partialdownsens,downacksens,upsens,warnsens,pausedsens,unusualsens,undefinedsens&count=2500&id=$StartingID&$auth"
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
    $getprtgGroupret = convertFrom-csv ($request)
    #write-host "got groups from website..."
    $getprtgGroupret
   
} # end function



##############################################
############Set-prtgDeviceProperty############
##############################################
# Sets a property of a device

function Set-prtgDeviceProperty ([string]$DeviceID,[string]$PropertyName,[string]$Value)
{
    $url = "https://$PRTGHost/api/setobjectproperty.htm?id=$DeviceID&name=$PropertyName&value=$Value&$auth"
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore


} # end function


##############################################
############Add-prtgSensorToDevice############
##############################################
# add's a sensor to a device (good for updating templates- adding a new sensor to 100's of devices)



#eg add one sensor to a group of devices
#add-prtgSensorToDevice -SensorScriptBlock {Get-prtgSensorInGroup | where {$_.id -eq 8328}} -DevicesScriptBlock {Get-prtgDevicesInGroup 7633}

#eg, add sensor 5520 to device 6409
#add-prtgSensorToDevice -SensorScriptBlock {Get-prtgSensorInGroup | where {$_.id -eq 5520}} -DevicesScriptBlock {Get-prtgDevicesInGroup | where {$_.id -eq 6409}}

#eg add a pages_left sensor to all devices with a tag of "printer"
#TODO

function Add-prtgSensorToDevice
{
    [CmdletBinding()]
    
    param(
            [Parameter(Mandatory=$False,ValueFromPipelineByPropertyName=$false)]
            [scriptblock]$DevicesScriptBlock,

            [Parameter(Mandatory=$False,ValueFromPipelineByPropertyName=$false)]
            [scriptblock]$SensorScriptBlock
          )

    process
    {
        
        if ($SensorScriptBlock -ne $null -and $DevicesScriptBlock -ne $null)
        {
            ##loop thru all the devices.
            $Devices = &([scriptblock]::Create($DevicesScriptBlock))
    
            foreach($Device in  $Devices)
            {
                $DeviceID = $device.id
                "DeviceID=$DeviceID"

                ##Loop thru all the sensors.
                $Sensors = &([scriptblock]::Create($SensorScriptBlock))
    
                foreach($Sensor in  $Sensors)
                {
                    $SensorID = $Sensor.id
                    "SensorID=$SensorID"
                    $NewName=$Sensor.Sensor
                    $url = "https://$PRTGHost/api/duplicateobject.htm?id=$SensorID&Targetid=$DeviceID&name=$NewName&$auth"
                    $url
                    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
                } # end foreach -  Sensor
            } # end foreach - Device

        } # end if

    } # end process

} # end function



##############################################
############Add-prtgDevice############
##############################################
# adds a new device in PRTG

#example
#Add-prtgDevice -NewIP "5.5.5.5" -TemplateID 5682 -DestGroupID 6408 -NewDeviceName "Hi_I_Am_New"

#example, import from CSV. where the fields are newip, TemplateID, DestGroupID, NewDeviceName
#Import-Csv -Delimiter "`t" -path c:\prtgimport.csv | Add-prtgDevice

function Add-prtgDevice 
{
 
    [CmdletBinding()]
    
    param(
            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$NewIP,

            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$TemplateID,

            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$DestGroupID,

            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$NewDeviceName
    
    
    )

    Process 
    {
        #$NeWIP = "2.2.2.2"
        #$TemplateID = "5539"
        #$DestGroupID = "5538"
        #$NewDeviceName = "Server1"

        "" + "adding sensor$NewIP"
        #Duplicate the sensor (Server replies with a redirect to new objects webpage, e.g. /sensor.htm?id=10214, parse id 10214 from the URL):
        $url = "https://$PRTGHost/api/duplicateobject.htm?id=$TemplateID&name=$NewDeviceName&targetid=$DestGroupID&$auth"
    
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
        $newID = $request.Headers.Location.Split("=")[1]

        #add in the correct IP (host) the new sensor:
        $url = "https://$PRTGHost/api/setobjectproperty.htm?id=$newID&name=host&value=$newIP&$auth" 
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore

        #Resume monitoring for the new sensor:
        $url = "https://$PRTGHost/api/pause.htm?id=$newID&action=1&$auth"
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
    } #end process
} # end function

api automate powershell-module

Created on Feb 22, 2016 1:31:47 AM

Last change on Feb 22, 2016 6:23:53 AM by  Stephan Linke [Paessler Support]



Best Answer

Accepted Answer

Votes:

11

Just posting an update to this Powershell Module:

What does this do?

  • Powers lots of other scripts
  • allows you to pause servers via code, including "Pause This Server"
  • allows you to bulk add (from CSV)
  • allows you to update comments of a object (device or sensor) from outside of PRTG
  • allows you to have advanced scheduling of thresholds
  • allows bulk adding of sensors to groups of devices

Change Log

2016/3/9:

Added Set-PRTGPauseThisServer and Set-PRTGReumeThisServer. This will get all IP addresses, hostname and FQDN and look for these addresses in the host field of all devices, once found it would it will pause the device(s) for a given amount of time.

Added Set-PRTGChannelSettings: allows you to change channel settings, such as limits.

Added Set-PRTGAdvancedSchedules: this allows devices to have different thresholds at different times of the day. Read more here: https://thedomainiown.wordpress.com/prtg-related/advanced-scheduling/

Code

The newest copy of the code will also be post here: https://thedomainiown.wordpress.com/prtg-related/prtg-script-powershell-admin-module/

A snapshot is provided below:

######ignore invalid SSL Certs##########
add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy2 : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

######setup details, access related.
$auth = "username=api_access&passhash=1669687025"
$PRTGHost = "192.168.0.89"



##############################################
############Get-prtgSensorInGroup#############
##############################################
# will return ALL sensors listed in PRTG, for a given Group (via its ID) (limited to 2500)
#default is the root (ID=0)
#its important to remember that a "Group" is also a device, and probe etc.
#eg
#Get-prtgSensorInGroup 8011

function Get-prtgSensorInGroup([string]$StartingID=0)
{
    $url = "http://$PRTGHost/api/table.xml?content=sensors&output=csvtable&columns=objid,probe,group,device,sensor,status,message,lastvalue,priority,favorite,tags&id=$StartingID&count=2500&$auth"
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore

    convertFrom-csv $request -WarningAction SilentlyContinue
} # end function




##############################################
############Get-prtgDevicesInGroup####################
##############################################
# will return ALL Devices listed in PRTG, for a given Group (via its ID) (limited to 2500)
#default is the root (ID=0)
#if you want to find 1 device(ID=8011), then use: Get-prtgDevicesInGroup | where {$_.ID -eq 8011}
#anther example, seaching for an IP
#Get-prtgDevicesInGroup | where {$_.host -eq "10.81.8.36"}

#you may also want to return many devices, eg
#Get-prtgDevicesInGroup | where {$_.host -like "10.81.8.*"}

function Get-prtgDevicesInGroup ([string]$StartingID=0)
{
    #if ($script:devicesCached -eq $false){
        $url = "http://$PRTGHost/api/table.xml?content=devices&output=csvtable&columns=objid,probe,groupid,device,host,downsens,partialdownsens,downacksens,upsens,warnsens,pausedsens,unusualsens,undefinedsens,comments&id=$StartingID&count=2500&$auth"
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
        $getprtgDeviceRet = convertFrom-csv ($request.content) -WarningAction SilentlyContinue
        $getprtgDeviceRet 
    #    write-host "got devices from website..."
    #    $script:devicesCached = $true
    #}else{
    #    write-host "got groups from cache..."
    #    $getprtgDeviceRet 
    #}
} # end function


##############################################
############Get-prtgGroupsInGroup####################
##############################################
# will return ALL Groups listed in PRTG, for a given Group (via its ID) (limited to 2500)
#default is the root (ID=0)

#will will list all the group recurively under the listed group (ie, not JUST the children)

#eg, return al lthe groups in the local probe
# get-prtgGroupsInGroup 1

function get-prtgGroupsInGroup ([string]$StartingID=0)
{
   
    $url = "http://$PRTGHost/api/table.xml?content=groups&output=csvtable&columns=objid,probe,group,name,downsens,partialdownsens,downacksens,upsens,warnsens,pausedsens,unusualsens,undefinedsens&count=2500&id=$StartingID&$auth"
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
    $getprtgGroupret = convertFrom-csv ($request) -WarningAction SilentlyContinue
    #write-host "got groups from website..."
    $getprtgGroupret
   
} # end function



##############################################
############Set-prtgDeviceProperty############
##############################################
# Sets a property of a device

function Set-prtgDeviceProperty ([string]$DeviceID,[string]$PropertyName,[string]$Value)
{
    $url = "http://$PRTGHost/api/setobjectproperty.htm?id=$DeviceID&name=$PropertyName&value=$Value&$auth"
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore


} # end function



##############################################
############Get-prtgDeviceProperty############
##############################################
# Gets a property of a device

function Get-prtgDeviceProperty ([string]$DeviceID,[string]$PropertyName)
{
    $url = "http://$PRTGHost/api/getobjectproperty.htm?id=$DeviceID&name=$PropertyName&$auth"
    [xml]$request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
    $request.ChildNodes.result

} # end function


##############################################
############Add-prtgSensorToDevice############
##############################################
# add's a sensor to a device (good for updating templates- adding a new sensor to 100's of devices)



#eg add one sensor to a group of devices
#add-prtgSensorToDevice -SensorScriptBlock {Get-prtgSensorInGroup | where {$_.id -eq 8328}} -DevicesScriptBlock {Get-prtgDevicesInGroup 7633}

#eg, add sensor 5520 to device 6409
#add-prtgSensorToDevice -SensorScriptBlock {Get-prtgSensorInGroup | where {$_.id -eq 5520}} -DevicesScriptBlock {Get-prtgDevicesInGroup | where {$_.id -eq 6409}}

#eg add a pages_left sensor to all devices with a tag of "printer"
#TODO

function Add-prtgSensorToDevice
{
    [CmdletBinding()]
    
    param(
            [Parameter(Mandatory=$False,ValueFromPipelineByPropertyName=$false)]
            [scriptblock]$DevicesScriptBlock,

            [Parameter(Mandatory=$False,ValueFromPipelineByPropertyName=$false)]
            [scriptblock]$SensorScriptBlock
          )

    process
    {
        
        if ($SensorScriptBlock -ne $null -and $DevicesScriptBlock -ne $null)
        {
            ##loop thru all the devices.
            $Devices = &([scriptblock]::Create($DevicesScriptBlock))
    
            foreach($Device in  $Devices)
            {
                $DeviceID = $device.id
                "DeviceID=$DeviceID"

                ##Loop thru all the sensors.
                $Sensors = &([scriptblock]::Create($SensorScriptBlock))
    
                foreach($Sensor in  $Sensors)
                {
                    $SensorID = $Sensor.id
                    "SensorID=$SensorID"
                    $NewName=$Sensor.Sensor
                    $url = "http://$PRTGHost/api/duplicateobject.htm?id=$SensorID&Targetid=$DeviceID&name=$NewName&$auth"
                    $url
                    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
                } # end foreach -  Sensor
            } # end foreach - Device

        } # end if

    } # end process

} # end function



##############################################
############Add-prtgDevice############
##############################################
# adds a new device in PRTG

#example
#Add-prtgDevice -NewIP "5.5.5.5" -TemplateID 5682 -DestGroupID 6408 -NewDeviceName "Hi_I_Am_New"

#example, import from CSV. where the fields are newip, TemplateID, DestGroupID, NewDeviceName
#Import-Csv -Delimiter "`t" -path c:\prtgimport.csv | Add-prtgDevice

function Add-prtgDevice 
{
 
    [CmdletBinding()]
    
    param(
            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$NewIP,

            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$TemplateID,

            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$DestGroupID,

            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$NewDeviceName
    
    
    )

    Process 
    {
        #$NeWIP = "2.2.2.2"
        #$TemplateID = "5539"
        #$DestGroupID = "5538"
        #$NewDeviceName = "Server1"

        "" + "adding sensor$NewIP"
        #Duplicate the sensor (Server replies with a redirect to new objects webpage, e.g. /sensor.htm?id=10214, parse id 10214 from the URL):
        $url = "http://$PRTGHost/api/duplicateobject.htm?id=$TemplateID&name=$NewDeviceName&targetid=$DestGroupID&$auth"
    
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
        $newID = $request.Headers.Location.Split("=")[1]

        #add in the correct IP (host) the new sensor:
        $url = "http://$PRTGHost/api/setobjectproperty.htm?id=$newID&name=host&value=$newIP&$auth" 
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore

        #Resume monitoring for the new sensor:
        $url = "http://$PRTGHost/api/pause.htm?id=$newID&action=1&$auth"
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
    } #end process
} # end function


##############################################
#######Get-PRTGActiveAdvancedSchedule#########
##############################################
#looks in the comments for a given sensor, and grabs what is between the "{AdvancedSchedule}" and "{/AdvancedSchedule}" tags.
# eg:
#{AdvancedSchedule}
#Channel,Start,Stop,UpperWarn,UpperError,LowerWarn,LowerError
#0,07:00,12:30,1,2,3,4
#0,12:31,6:59,5,6,7,8
#{/AdvancedSchedule}
#

Function Get-PRTGActiveAdvancedSchedule{
    param
    (
        $DeviceID
    )

    ##get the comments
    [string]$ret = Get-prtgDeviceProperty -DeviceID $DeviceID -PropertyName comments

    #strip the headers
    $q1 = $ret.IndexOf("{AdvancedSchedule}")
    $q2 = $ret.IndexOf("{/AdvancedSchedule}")
    $ret = $ret.Substring($q1+18,($q2-$q1)-18)
    
    #$ret = $ret.Replace("{AdvancedSchedule}","")
    #$ret = $ret.Replace("{/AdvancedSchedule}","")

    #get rid of the blank lines
    $ret2 = $ret -creplace '(?m)^\s*\r?\n',''
    
    $ret3 = convertFrom-csv ($ret2)

    #return just the active entries
    $ret3 | where {$_.start -lt (get-date).TimeOfDay -and $_.stop -gt (get-date).TimeOfDay}
    

}


##############################################
###########Set-PRTGChannelSettings############
##############################################

#warning: this is not part of the standard API - and might be removed at any time.
#warning: this is really useful!
#this lets you update channel properties. To get a list of properties you can change you will
# need to examine the post data (using browser tools) when making changes to a channel via the PRTG web interface.

function Set-PRTGChannelSettings{
    param(
    $DeviceID, 
    $ChannelID,
    $Property,
    $Value
    )

    $url = "http://$PRTGHost/editsettings?$Property" + "_" + $ChannelID + "=" + "$value&id=$DeviceID&$auth"
    #$url
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
}

function Set-PRTGAdvancedSchedules{
    $DeviceswithAdvancedSchedules = Get-prtgSensorInGroup | where {$_.Tags -like "*AdvancedSchedule*"}
    Foreach ($Device in $DeviceswithAdvancedSchedules){
	    $Schedules = Get-PRTGActiveAdvancedSchedule -DeviceID $Device.ID
	    Foreach ($Schedule in $Schedules){
		    If ($Schedule.UpperError -ne ""){
			    Set-PRTGChannelSettings -DeviceID $Device.ID -ChannelID $Schedule.channel -Property limitmaxerror -Value $Schedule.UpperError
		    }
            If ($Schedule.LowerError -ne ""){
			    Set-PRTGChannelSettings -DeviceID $Device.ID -ChannelID $Schedule.channel -Property limitminerror -Value $Schedule.LowerError
		    }
            If ($Schedule.UpperWarn -ne ""){
			    Set-PRTGChannelSettings -DeviceID $Device.ID -ChannelID $Schedule.channel -Property limitmaxwarning -Value $Schedule.UpperWarn
		    }
            If ($Schedule.LowerWarn -ne ""){
			    Set-PRTGChannelSettings -DeviceID $Device.ID -ChannelID $Schedule.channel -Property limitminwarning -Value $Schedule.LowerWarn
		    }
	    }
    }

}


#example:
#Set-PRTGObjectPause -ObjectID 2003 -Minutes 5 -Message "Please Wait - Server Rebooting"
function Set-PRTGObjectPause{
    param
    (
    $ObjectID,
    $Message,
    $Minutes
    )
    ##ObjectID can be a sensor, device or Group
    $url = "http://$PRTGHost/api/pauseobjectfor.htm?id=$ObjectID&duration=$minutes&pausemsg=$Message&$auth"
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore

}

function Set-PRTGPauseThisServer{
    param
    (
    $Message,
    $Minutes
    )
    $myIPs = Get-NetIPAddress -AddressFamily IPv4 | where { $_.InterfaceAlias -notmatch 'Loopback'} |Select IPAddress
    
    $t = "" | select ipaddress 
    $t.ipaddress = hostname
    $myips += $t

    $t = "" | select ipaddress 
    $t.ipaddress = "$env:computername.$env:userdnsdomain"
    $myips += $t


    #$myips
    foreach ($ip in $MYIPs){
        $q = Get-prtgDevicesInGroup | where {$_.host -eq $IP.ipaddress} 

        foreach ($x in $q){
            Set-PRTGObjectPause -ObjectID $x.ID -Minutes $Minutes -Message "$Message"
        }
    }
}


function Set-PRTGResumeThisServer{
    $myIPs = Get-NetIPAddress -AddressFamily IPv4 | where { $_.InterfaceAlias -notmatch 'Loopback'} |Select IPAddress
    
    $t = "" | select ipaddress 
    $t.ipaddress = hostname
    $myips += $t

    $t = "" | select ipaddress 
    $t.ipaddress = "$env:computername.$env:userdnsdomain"
    $myips += $t


    #$myips
    foreach ($ip in $MYIPs){
        $q = Get-prtgDevicesInGroup | where {$_.host -eq $IP.ipaddress} 

        foreach ($x in $q){
            $url = "http://$PRTGHost/api/pause.htm?id=" + $x.ID + "&action=1&$auth"
            $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
        }
    }
}

Created on Mar 9, 2016 10:44:36 AM



5 Replies

Votes:

0

Thanks for publishing your work! :) There's also PRTGShell which might help you on this on future projects :)

Created on Feb 22, 2016 7:41:25 AM by  Stephan Linke [Paessler Support]

Last change on Feb 22, 2016 7:41:36 AM by  Stephan Linke [Paessler Support]



Accepted Answer

Votes:

11

Just posting an update to this Powershell Module:

What does this do?

  • Powers lots of other scripts
  • allows you to pause servers via code, including "Pause This Server"
  • allows you to bulk add (from CSV)
  • allows you to update comments of a object (device or sensor) from outside of PRTG
  • allows you to have advanced scheduling of thresholds
  • allows bulk adding of sensors to groups of devices

Change Log

2016/3/9:

Added Set-PRTGPauseThisServer and Set-PRTGReumeThisServer. This will get all IP addresses, hostname and FQDN and look for these addresses in the host field of all devices, once found it would it will pause the device(s) for a given amount of time.

Added Set-PRTGChannelSettings: allows you to change channel settings, such as limits.

Added Set-PRTGAdvancedSchedules: this allows devices to have different thresholds at different times of the day. Read more here: https://thedomainiown.wordpress.com/prtg-related/advanced-scheduling/

Code

The newest copy of the code will also be post here: https://thedomainiown.wordpress.com/prtg-related/prtg-script-powershell-admin-module/

A snapshot is provided below:

######ignore invalid SSL Certs##########
add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy2 : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
        }
    }
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

######setup details, access related.
$auth = "username=api_access&passhash=1669687025"
$PRTGHost = "192.168.0.89"



##############################################
############Get-prtgSensorInGroup#############
##############################################
# will return ALL sensors listed in PRTG, for a given Group (via its ID) (limited to 2500)
#default is the root (ID=0)
#its important to remember that a "Group" is also a device, and probe etc.
#eg
#Get-prtgSensorInGroup 8011

function Get-prtgSensorInGroup([string]$StartingID=0)
{
    $url = "http://$PRTGHost/api/table.xml?content=sensors&output=csvtable&columns=objid,probe,group,device,sensor,status,message,lastvalue,priority,favorite,tags&id=$StartingID&count=2500&$auth"
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore

    convertFrom-csv $request -WarningAction SilentlyContinue
} # end function




##############################################
############Get-prtgDevicesInGroup####################
##############################################
# will return ALL Devices listed in PRTG, for a given Group (via its ID) (limited to 2500)
#default is the root (ID=0)
#if you want to find 1 device(ID=8011), then use: Get-prtgDevicesInGroup | where {$_.ID -eq 8011}
#anther example, seaching for an IP
#Get-prtgDevicesInGroup | where {$_.host -eq "10.81.8.36"}

#you may also want to return many devices, eg
#Get-prtgDevicesInGroup | where {$_.host -like "10.81.8.*"}

function Get-prtgDevicesInGroup ([string]$StartingID=0)
{
    #if ($script:devicesCached -eq $false){
        $url = "http://$PRTGHost/api/table.xml?content=devices&output=csvtable&columns=objid,probe,groupid,device,host,downsens,partialdownsens,downacksens,upsens,warnsens,pausedsens,unusualsens,undefinedsens,comments&id=$StartingID&count=2500&$auth"
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
        $getprtgDeviceRet = convertFrom-csv ($request.content) -WarningAction SilentlyContinue
        $getprtgDeviceRet 
    #    write-host "got devices from website..."
    #    $script:devicesCached = $true
    #}else{
    #    write-host "got groups from cache..."
    #    $getprtgDeviceRet 
    #}
} # end function


##############################################
############Get-prtgGroupsInGroup####################
##############################################
# will return ALL Groups listed in PRTG, for a given Group (via its ID) (limited to 2500)
#default is the root (ID=0)

#will will list all the group recurively under the listed group (ie, not JUST the children)

#eg, return al lthe groups in the local probe
# get-prtgGroupsInGroup 1

function get-prtgGroupsInGroup ([string]$StartingID=0)
{
   
    $url = "http://$PRTGHost/api/table.xml?content=groups&output=csvtable&columns=objid,probe,group,name,downsens,partialdownsens,downacksens,upsens,warnsens,pausedsens,unusualsens,undefinedsens&count=2500&id=$StartingID&$auth"
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
    $getprtgGroupret = convertFrom-csv ($request) -WarningAction SilentlyContinue
    #write-host "got groups from website..."
    $getprtgGroupret
   
} # end function



##############################################
############Set-prtgDeviceProperty############
##############################################
# Sets a property of a device

function Set-prtgDeviceProperty ([string]$DeviceID,[string]$PropertyName,[string]$Value)
{
    $url = "http://$PRTGHost/api/setobjectproperty.htm?id=$DeviceID&name=$PropertyName&value=$Value&$auth"
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore


} # end function



##############################################
############Get-prtgDeviceProperty############
##############################################
# Gets a property of a device

function Get-prtgDeviceProperty ([string]$DeviceID,[string]$PropertyName)
{
    $url = "http://$PRTGHost/api/getobjectproperty.htm?id=$DeviceID&name=$PropertyName&$auth"
    [xml]$request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
    $request.ChildNodes.result

} # end function


##############################################
############Add-prtgSensorToDevice############
##############################################
# add's a sensor to a device (good for updating templates- adding a new sensor to 100's of devices)



#eg add one sensor to a group of devices
#add-prtgSensorToDevice -SensorScriptBlock {Get-prtgSensorInGroup | where {$_.id -eq 8328}} -DevicesScriptBlock {Get-prtgDevicesInGroup 7633}

#eg, add sensor 5520 to device 6409
#add-prtgSensorToDevice -SensorScriptBlock {Get-prtgSensorInGroup | where {$_.id -eq 5520}} -DevicesScriptBlock {Get-prtgDevicesInGroup | where {$_.id -eq 6409}}

#eg add a pages_left sensor to all devices with a tag of "printer"
#TODO

function Add-prtgSensorToDevice
{
    [CmdletBinding()]
    
    param(
            [Parameter(Mandatory=$False,ValueFromPipelineByPropertyName=$false)]
            [scriptblock]$DevicesScriptBlock,

            [Parameter(Mandatory=$False,ValueFromPipelineByPropertyName=$false)]
            [scriptblock]$SensorScriptBlock
          )

    process
    {
        
        if ($SensorScriptBlock -ne $null -and $DevicesScriptBlock -ne $null)
        {
            ##loop thru all the devices.
            $Devices = &([scriptblock]::Create($DevicesScriptBlock))
    
            foreach($Device in  $Devices)
            {
                $DeviceID = $device.id
                "DeviceID=$DeviceID"

                ##Loop thru all the sensors.
                $Sensors = &([scriptblock]::Create($SensorScriptBlock))
    
                foreach($Sensor in  $Sensors)
                {
                    $SensorID = $Sensor.id
                    "SensorID=$SensorID"
                    $NewName=$Sensor.Sensor
                    $url = "http://$PRTGHost/api/duplicateobject.htm?id=$SensorID&Targetid=$DeviceID&name=$NewName&$auth"
                    $url
                    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
                } # end foreach -  Sensor
            } # end foreach - Device

        } # end if

    } # end process

} # end function



##############################################
############Add-prtgDevice############
##############################################
# adds a new device in PRTG

#example
#Add-prtgDevice -NewIP "5.5.5.5" -TemplateID 5682 -DestGroupID 6408 -NewDeviceName "Hi_I_Am_New"

#example, import from CSV. where the fields are newip, TemplateID, DestGroupID, NewDeviceName
#Import-Csv -Delimiter "`t" -path c:\prtgimport.csv | Add-prtgDevice

function Add-prtgDevice 
{
 
    [CmdletBinding()]
    
    param(
            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$NewIP,

            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$TemplateID,

            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$DestGroupID,

            [Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$true)]
            [string]$NewDeviceName
    
    
    )

    Process 
    {
        #$NeWIP = "2.2.2.2"
        #$TemplateID = "5539"
        #$DestGroupID = "5538"
        #$NewDeviceName = "Server1"

        "" + "adding sensor$NewIP"
        #Duplicate the sensor (Server replies with a redirect to new objects webpage, e.g. /sensor.htm?id=10214, parse id 10214 from the URL):
        $url = "http://$PRTGHost/api/duplicateobject.htm?id=$TemplateID&name=$NewDeviceName&targetid=$DestGroupID&$auth"
    
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
        $newID = $request.Headers.Location.Split("=")[1]

        #add in the correct IP (host) the new sensor:
        $url = "http://$PRTGHost/api/setobjectproperty.htm?id=$newID&name=host&value=$newIP&$auth" 
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore

        #Resume monitoring for the new sensor:
        $url = "http://$PRTGHost/api/pause.htm?id=$newID&action=1&$auth"
        $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
    } #end process
} # end function


##############################################
#######Get-PRTGActiveAdvancedSchedule#########
##############################################
#looks in the comments for a given sensor, and grabs what is between the "{AdvancedSchedule}" and "{/AdvancedSchedule}" tags.
# eg:
#{AdvancedSchedule}
#Channel,Start,Stop,UpperWarn,UpperError,LowerWarn,LowerError
#0,07:00,12:30,1,2,3,4
#0,12:31,6:59,5,6,7,8
#{/AdvancedSchedule}
#

Function Get-PRTGActiveAdvancedSchedule{
    param
    (
        $DeviceID
    )

    ##get the comments
    [string]$ret = Get-prtgDeviceProperty -DeviceID $DeviceID -PropertyName comments

    #strip the headers
    $q1 = $ret.IndexOf("{AdvancedSchedule}")
    $q2 = $ret.IndexOf("{/AdvancedSchedule}")
    $ret = $ret.Substring($q1+18,($q2-$q1)-18)
    
    #$ret = $ret.Replace("{AdvancedSchedule}","")
    #$ret = $ret.Replace("{/AdvancedSchedule}","")

    #get rid of the blank lines
    $ret2 = $ret -creplace '(?m)^\s*\r?\n',''
    
    $ret3 = convertFrom-csv ($ret2)

    #return just the active entries
    $ret3 | where {$_.start -lt (get-date).TimeOfDay -and $_.stop -gt (get-date).TimeOfDay}
    

}


##############################################
###########Set-PRTGChannelSettings############
##############################################

#warning: this is not part of the standard API - and might be removed at any time.
#warning: this is really useful!
#this lets you update channel properties. To get a list of properties you can change you will
# need to examine the post data (using browser tools) when making changes to a channel via the PRTG web interface.

function Set-PRTGChannelSettings{
    param(
    $DeviceID, 
    $ChannelID,
    $Property,
    $Value
    )

    $url = "http://$PRTGHost/editsettings?$Property" + "_" + $ChannelID + "=" + "$value&id=$DeviceID&$auth"
    #$url
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
}

function Set-PRTGAdvancedSchedules{
    $DeviceswithAdvancedSchedules = Get-prtgSensorInGroup | where {$_.Tags -like "*AdvancedSchedule*"}
    Foreach ($Device in $DeviceswithAdvancedSchedules){
	    $Schedules = Get-PRTGActiveAdvancedSchedule -DeviceID $Device.ID
	    Foreach ($Schedule in $Schedules){
		    If ($Schedule.UpperError -ne ""){
			    Set-PRTGChannelSettings -DeviceID $Device.ID -ChannelID $Schedule.channel -Property limitmaxerror -Value $Schedule.UpperError
		    }
            If ($Schedule.LowerError -ne ""){
			    Set-PRTGChannelSettings -DeviceID $Device.ID -ChannelID $Schedule.channel -Property limitminerror -Value $Schedule.LowerError
		    }
            If ($Schedule.UpperWarn -ne ""){
			    Set-PRTGChannelSettings -DeviceID $Device.ID -ChannelID $Schedule.channel -Property limitmaxwarning -Value $Schedule.UpperWarn
		    }
            If ($Schedule.LowerWarn -ne ""){
			    Set-PRTGChannelSettings -DeviceID $Device.ID -ChannelID $Schedule.channel -Property limitminwarning -Value $Schedule.LowerWarn
		    }
	    }
    }

}


#example:
#Set-PRTGObjectPause -ObjectID 2003 -Minutes 5 -Message "Please Wait - Server Rebooting"
function Set-PRTGObjectPause{
    param
    (
    $ObjectID,
    $Message,
    $Minutes
    )
    ##ObjectID can be a sensor, device or Group
    $url = "http://$PRTGHost/api/pauseobjectfor.htm?id=$ObjectID&duration=$minutes&pausemsg=$Message&$auth"
    $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore

}

function Set-PRTGPauseThisServer{
    param
    (
    $Message,
    $Minutes
    )
    $myIPs = Get-NetIPAddress -AddressFamily IPv4 | where { $_.InterfaceAlias -notmatch 'Loopback'} |Select IPAddress
    
    $t = "" | select ipaddress 
    $t.ipaddress = hostname
    $myips += $t

    $t = "" | select ipaddress 
    $t.ipaddress = "$env:computername.$env:userdnsdomain"
    $myips += $t


    #$myips
    foreach ($ip in $MYIPs){
        $q = Get-prtgDevicesInGroup | where {$_.host -eq $IP.ipaddress} 

        foreach ($x in $q){
            Set-PRTGObjectPause -ObjectID $x.ID -Minutes $Minutes -Message "$Message"
        }
    }
}


function Set-PRTGResumeThisServer{
    $myIPs = Get-NetIPAddress -AddressFamily IPv4 | where { $_.InterfaceAlias -notmatch 'Loopback'} |Select IPAddress
    
    $t = "" | select ipaddress 
    $t.ipaddress = hostname
    $myips += $t

    $t = "" | select ipaddress 
    $t.ipaddress = "$env:computername.$env:userdnsdomain"
    $myips += $t


    #$myips
    foreach ($ip in $MYIPs){
        $q = Get-prtgDevicesInGroup | where {$_.host -eq $IP.ipaddress} 

        foreach ($x in $q){
            $url = "http://$PRTGHost/api/pause.htm?id=" + $x.ID + "&action=1&$auth"
            $request = Invoke-WebRequest -Uri $url -MaximumRedirection 0 -ErrorAction Ignore
        }
    }
}

Created on Mar 9, 2016 10:44:36 AM



Votes:

1

Love the powershell, just wanted to add, if you want to add a v6 device, use the following command:

"http://$PRTGHost/api/setobjectproperty.htm?id=$newID&name=hostv6&value=$newIP&$auth"

Spent a while looking for it, just had to use firebug and find that "hostv6" was the proper name to use when adding.

Thanks for the powershell!

Created on Sep 24, 2017 8:38:09 PM

Last change on Sep 25, 2017 5:10:29 AM by  Luciano Lingnau [Paessler]



Votes:

0

Thanks for sharing the improvement!

Ill try to work this in the next update i do.

Created on Sep 26, 2017 1:06:17 AM



Votes:

0

This is an old post. lordmilko has produced this very fine PowerShell module: https://github.com/lordmilko/PrtgAPI

Created on Sep 2, 2019 11:05:35 AM




Disclaimer: The information in the Paessler Knowledge Base comes without warranty of any kind. Use at your own risk. Before applying any instructions please exercise proper system administrator housekeeping. You must make sure that a proper backup of all your data is available.