Object Creation

lordmilko edited this page Feb 17, 2019 · 96 revisions

Contents

C#

Sensor Creation

PrtgAPI is capable of creating brand new instances of all sensor types supported by PRTG. Due to the sheer number of available sensor types however, PrtgAPI only includes native support for a limited subset of this range. For all other sensor types, PrtgAPI defines an interface that allows custom sensor parameters to be generated and created.

In order to add a sensor you must first create a NewSensorParameters object of the sensor type you wish to add.

PrtgAPI natively supports the creation of the following sensor types:

  • EXE/Script Advanced
  • WMI Service
  • HTTP

For all other sensor types please see Dynamic Parameters

//Create a new EXE/Script Advanced sensor under the device with ID 1001
var parameters = new ExeXmlSensorParameters("testScript.ps1");

var sensors = client.AddSensor(1001, parameters);

All properties unique to a given sensor type the parameters object's constructor. Any values that are not specified will be instantiated with their default values (shown via IntelliSense). Properties common to all sensor types will automatically be instantiated with the default values given to them across all sensors, and can be modified via an object initializer or after the object has been instantiated

var parameters = new ExeXmlSensorParameters("testScript.ps1")
{
    Interval = ScanningInterval.FiveMinutes
};

PrtgAPI is capable of querying PRTG for a list of supported sensor targets that can be used with a new sensor (such as a list of EXE/Script files present on a device's probe, or a list of WMI Services that are installed on a device). For more information, see Sensor Targets.

In order to add a sensor, call the AddSensor method with the ID of the device the sensor will apply to, as well as the parameters that define the sensor to create.

//You can specify values either in the constructor, or via object initialization
var parameters = new ExeXmlSensorParameters("super important.ps1", "Super Important Script!")
{
    ExeParameters = "dc-1 2000",
    Mutex = "superimportant1",
    Timeout = 70,
    Interval = ScanningInterval.FiveMinutes
};

//Add the sensor to the device with ID 2001
var sensors = client.AddSensor(2001, parameters);

Parameters that are required by a sensor (such as the ExeFile of an EXE/Script Advanced sensor) are validated by AddSensor when the sensor is added. If a required field is missing a value, PrtgAPI will throw an InvalidOperationException specifying the property whose value was invalid.

By default PrtgAPI will resolve any new sensors to their resultant Sensor objects. Based on the type of sensor parameters specified, one or more sensors will be returned. If you do not wish to perform object resolution, this behavior can be disabled by setting the optional parameter resolve to false. If object resolution is disabled, AddSensor will return null.

//Add new sensors to the object with ID 2001 without resolving them
client.AddSensor(2001, parameters, false);

When resolving added sensors, for accuracy and performance purposes PrtgAPI limits its search to sensors that have the same Type specified in the NewSensorParameters object. If you are creating a sensor with a dynamic sensor type that changes based on exact parameters that are specified (such as snmplibrary) you should set the DynamicType property of the parameters object to true.

parameters.DynamicType = true;

For information on creating custom sensor parameter objects for creating sensor types not currently supported by PrtgAPI, see Dynamic Parameters and Custom Parameters.

Device Creation

A brand new device can be created under an existing group or probe via the AddDevice method.

The easiest way to create a new device is to call AddDevice with a parent ID and name, optionally specifying the host and optional auto-discovery mode. If the host is not specified, the name of the device will be used as a hostname.

var device = client.AddDevice(3001, "dc-1", "192.168.0.1", AutoDiscoveryMode.Automatic);

For scenarios in which you wish to specify more advanced properties at the time of object creation, a set of NewDeviceParameters must be created specifying the settings to use on the new device.

var parameters = new NewDeviceParameters("dc-1", "192.168.0.1")
{
    AutoDiscoveryMode = AutoDiscoveryMode.Automatic,
    AutoDiscoverySchedule = AutoDiscoverySchedule.Weekly
};

var device = client.AddDevice(3001, parameters);

While the PRTG UI allows specifying a vast array of properties on a device at the time of creation, for maintainability purposes PrtgAPI only supports the most critical properties pertinent to device objects. If you wish to modify any other properties of the device, this can be done so after the device is created via the SetObjectProperty method.

By default PrtgAPI will resolve any new devices to their resultant Device objects. As PRTG does not return any information about the created devices, PrtgAPI uses a diff based resolution mechanism to identify the newly created object. In the event an identical device is created under the specified parent object while resolution is occurring, PrtgAPI will throw an ObjectResolutionException specifying the Object IDs of the devices found. If you do not wish to perform object resolution, this behavior can be disabled by setting the optional parameter resolve to false. If object resolution is disabled, AddDevice will return null.

//Add a new device without resolving it
client.AddDevice(1001, "dc-1", resolve: false);

Group Creation

A brand new group can be created under an existing group or probe via the AddGroup method.

The easiest way to create a new group is to call AddGroup with just a parent ID and a name.

//Create a new group named "Servers" under the object with ID 3003
var group = client.AddGroup(3003, "Servers");

For scenarios in which you wish to specify more advanced properties at the time of object creation, a set of NewGroupParameters must be created specifying the settings to use on the new group.

//Create a new group named "Servers" under the object with ID 3003
var parameters = new NewGroupParameters("Servers")
{
    Tags = new[] { "CoreInfrastructure" }
};

var group = client.AddGroup(3003, parameters);

While the PRTG UI allows specifying a vast array of properties on a group at the time of creation, for maintainability purposes PrtgAPI only supports the most critical properties pertinent to group objects. If you wish to modify any other properties of the group, this can be done so after the group is created via the SetObjectProperty method.

By default PrtgAPI will resolve any new groups to their resultant Group objects. As PRTG does not return any information about the created group, PrtgAPI uses a diff based resolution mechanism to identify the newly created object. In the event an identical group is created under the specified parent object while resolution is occurring, PrtgAPI will throw an ObjectResolutionException specifying the Object IDs of the groups found. If you do not wish to perform object resolution, this behavior can be disabled by setting the optional parameter resolve to false. If object resolution is disabled, AddGroup will return null.

//Create a new group named "Servers" under the object with ID 3003 without resolving it
client.AddGroup(3003, "Servers", false);

Cloning

Sensors, Devices and Groups are capable of being cloned with PrtgAPI via the CloneObject method.

//Clone the device named "dc-1" to a new device called "dc-2" specifying the
//IP Address/HostName of the new server to be 192.168.0.2 and storing the new
//device under the same group or probe as the original

var device = client.GetDevices(Property.Name, "dc-1").First();

var newDeviceId = client.CloneObject(device.Id, "dc-2", "192.168.0.2", device.ParentId);
//Clone the sensor with ID 1001 under its parent device, naming the new sensor
//"Clone of <original name>"
var sensor = client.GetSensors(Property.Id, 1001).First();

var newSensorId = client.CloneObject(sensor.Id, $"Clone of {sensor}", sensor.ParentId);

When an object is cloned PRTG will return the object ID of the resultant object. As cloned objects are paused by default, you will likely want to execute a Resume request via the ResumeObject method

client.ResumeObject(newSensorId);

Note: upon resuming a cloned device, PRTG may automatically perform an auto-discovery of the cloned device depending on the auto-discovery mode of the device. This property can be modified in bulk by setting the AutoDiscoveryMode property to Manual. For more information, see Property Manipulation.

Note however that depending on the speed of your PRTG install, PRTG may take some time to actually finalize creating the object. If an object is still in the process of being created, any attempts to retrieve the new object will return nothing. This can be remediated by executing repeated requests until the object can be resolved

//Try real hard to resolve the desired object

List<Sensor> sensors;
var delay = 3;

//Loop until the object is resolved. In a real program you may wish to limit the total
//number of retries
do
{
    sensors = client.GetSensors(Property.Id, newSensorId);

    //If the object hasn't been created yet, we'll sleep for a few seconds to give the
    //object more time to create. With each successive fail we wait twice as long as
    //before
    if(sensors.Count == 0)
    {
        Thread.Sleep(delay * 1000);
        delay *= 2;
    }
} while(sensors.Count == 0);

client.ResumeObject(sensors.First().Id);

Auto-Discovery

If an auto-discovery has not been run on a device yet, or you wish to re-run an auto-discovery you can do so using the AutoDiscover method.

//Initiate an auto-discovery on the device with ID 1001
client.AutoDiscover(1001);

Auto-discoveries can be limited in scope to one or more device templates

//Perform an auto-discovery with all WMI Device Templates
var templates = client.GetDeviceTemplates().Where(t => t.Name.Contains("WMI")).ToArray();
client.AutoDiscover(1001, templates);

Depending on the size of your PRTG installation, auto-discovery operations can cause significant performance issues on your core server. As such care should be taken when programmatically initiating multiple auto-discovery operations. PRTG will only execute a maximum of 10 auto-discovery operations at once. If more than 10 auto-discovery operations are requested, PRTG will queue all operations and initiate them as slots become available.

PowerShell

Sensor Creation

PrtgAPI is capable of creating brand new instances of all sensor types supported by PRTG. Due to the sheer number of available sensor types however, PrtgAPI only includes native support for a limited subset of this range. For all other sensor types, PrtgAPI defines an interface that allows custom sensor parameters to be generated and created.

In order to add a sensor you must first create a NewSensorParameters object of the sensor type you wish to add.

Sensor parameters can be created with the New-SensorParameters cmdlet.

PrtgAPI natively supports the creation of the following sensor types:

  • EXE/Script Advanced
  • WMI Service
  • HTTP
# Create a new set of parameters for creating a new EXE/Script Advanced sensor
$params = New-SensorParameters ExeXml "Awesome Sensor"

For information on creating sensor types not natively supported by PrtgAPI please see Dynamic Parameters.

When creating native sensor parameters, at a minimum the sensor type must be specified. New-SensorParameters supports specifying two values (-First and -Second) for populating the most critical fields of the sensor (typically its name and target). If a name is required and -First is not specified, the parameters will use the default name PRTG would use for the specified sensor type.

For more information on how -First and -Second are used for each sensor type, see Get-Help SensorParameters

# Create a new set of sensor parameters, specifying the script name as a
# cmdlet parameter
$params = New-SensorParameters ExeXml "Awesome Sensor" "testScript.ps1"

# Create a new set of sensor parameters, specifying the script name at a
# later point in time
$params = New-SensorParameters ExeXml "Awesome Sensor"
$params.ExeFile = "testScript.ps1"

PrtgAPI is capable of querying PRTG for certain sensor types for a list of all supported sensor targets that can be used with that sensor (such as a list of EXE/Script files present on a device's probe, or a list of WMI Services that are installed on a device). For more information, see Sensor Targets.

Once a set of sensor parameters have been constructed, sensors can be added to one or more objects via the Add-Sensor cmdlet.

# Add a new EXE/Script Advanced sensor to the device with ID 1001
C:\> $params = New-SensorParameters ExeXml "Test" "test.ps1"
C:\> Get-Device -Id 1001 | Add-Sensor $params

Name               Id      Device      Group           Probe           Status
----               --      ------      -----           -----           ------
Test               2010    dc1         Servers         Local Probe     Up

By default Add-Sensor will attempt to resolve the new sensor created under the parent device. As PRTG does not return the ID of the created object, PrtgAPI achieves this by diffing the sensors present under the device before and after the sensor is created. While this is generally very reliable, in the event something or someone else creates another new sensor with the same name under the parent device in the time period between the first and second diff, that object will also be returned in objects returned by Add-Sensor. If you do not wish to resolve the created object, this behavior can be disabled by specifying -Resolve:$false.

Parameters that are required by the sensor (such as the ExeFile of an EXE/Script Advanced sensor) are validated by Add-Sensor when the sensor is added. If a required field is missing a value, PrtgAPI will throw an InvalidOperationException specifying the property whose value was invalid.

When resolving added sensors, for accuracy and performance purposes PrtgAPI limits its search to sensors that have the same Type specified in the NewSensorParameters object. If you are creating a sensor with a dynamic sensor type that changes based on exact parameters that are specified (such as snmplibrary) you should set the DynamicType property of the parameters object to true. This can be done at the time of parameter creation via the -DynamicType parameter

$params = $device | New-SensorParameters -RawType snmplibrary -DynamicType

or after the object has been created by setting the DynamicType property to $true

$params.DynamicType = $true

For information on creating custom sensor parameter objects for creating sensor types not currently supported by PrtgAPI, see Dynamic Parameters and Custom Parameters.

Device Creation

A brand new device can be created under an existing group or probe via the Add-Device cmdlet.

# Add a new device named "dc-1" with IP Address 192.168.0.1 under the
# probe named "contoso", performing an auto-discovery when created
C:\> Get-Probe contoso | Add-Device dc-1 192.168.0.1 -AutoDiscover

Name                Id      Status            Group           Probe
----                --      ------            -----           -----
dc-1                2197    Up                Contoso         Contoso

If a Host is not specified, Add-Device will automatically use the Name of the device as the hostname. Add-Device does not support creating devices with IPv6 Addresses. If you wish to specify an IPv6 Address, this can be done via Set-ObjectProperty

# Create a new device named "dc-1" and change its Host to an IPv6 Address
$device = Get-Probe contoso | Add-Device dc-1
$device | Set-ObjectProperty Hostv6 "2001:db8:370:7334" -PassThru | Start-AutoDiscovery

When -AutoDiscover is specified, one or more device templates may optionally be specified, allowing the initial auto-discovery to be limited in scope

Get-Probe contoso | Add-Device dc-1 -AutoDiscover -Template *wmi*,*rdp*

Device templates supported by PRTG can be viewed with the Get-DeviceTemplate cmdlet.

For scenarios in which you wish to specify advanced properties of a device at the time of device creation (such as the auto-discovery schedule or use IPv6 without having to call Set-ObjectProperty) this can be performed by creating a set of NewDeviceParameters via the New-DeviceParameters cmdlet.

# Create a new device named "dc-1" with an IPv6 Address
$params = New-DeviceParameters dc-1 "2001:db8:370:7334"
$params.IPVersion = "IPv6"
Get-Probe contoso | Add-Device $params

By default Add-Device will attempt to resolve the new device created under the parent object. As PRTG does not return the ID of the created object, PrtgAPI achieves this by diffing the devices present under the parent before and after the device is created. While this is generally very reliable, in the event something or someone else creates another new device with the same name under the parent object in the time period between the first and second diff, PrtgAPI will throw an ObjectResolutionException specifying the names and Object IDs of the objects found. If you do not wish to resolve the created object, this behavior can be disabled by specifying -Resolve:$false.

Group Creation

A brand new device can be created under an existing group or probe via the Add-Group cmdlet.

C:\> Get-Probe contoso | Add-Group Servers

Name      Id      Status    Probe      Devices    Up        Down  Down    Warning  Paused
                                                                  Sensors          (Ack)
----      --      ------    -----      -------    --------  ----  -----   -------  ------
Servers   2070    Up        Contoso    0          0         0     0       0        0

For scenarios in which you wish to specify advanced properties of a group at the time of group creation this can be performed by creating a set of NewGroupParameters via the New-GroupParameters cmdlet.

# Add a new group called "Servers" to the Contoso probe with a custom
# tag "awesomeGroup"
$params = New-GroupParameters Servers
$params.Tags = "awesomeGroup"
Get-Probe contoso | Add-Group $params

By default Add-Group will attempt to resolve the new group created under the parent object. As PRTG does not return the ID of the created object, PrtgAPI achieves this by diffing the groups present under the parent before and after the group is created. While this is generally very reliable, in the event something or someone else creates another new groupwith the same name under the parent object in the time period between the first and second diff, PrtgAPI will throw an ObjectResolutionException specifying the names and Object IDs of the objects found. If you do not wish to resolve the created object, this behavior can be disabled by specifying -Resolve:$false.

Cloning

Sensors, Devices, Groups and Triggers can be cloned with PrtgAPI via the Clone-Object cmdlet.

Clone-Object supports two modes of cloning

  • Clone From: <source> | Clone-Object -DestinationId <destination>
  • Clone To: <destination> | Clone-Object -SourceId <source>

If neither -DestinationId or -SourceId are specified (i.e. $obj | Clone-Object 1234) Clone-Object will default to Clone From mode.

Clone From

In Clone From mode, one or more source objects are cloned from somewhere to a specified destination ID

# Clone a ping sensor into the device with ID 1001
$newSensor = Get-Sensor ping -count 1 | Clone-Object -DestinationId 1001

When cloning sensors and groups, typically you want the new object to be the same as the old (just present under a new parent). As such, if a custom name is not specified PrtgAPI will automatically use the name of the input object. When cloning devices however you typically wish to modify the device to point to a new system; as such, if a custom device name is not specified PrtgAPI will automatically name the new object Clone of <device name>

# Clone all WMI CPU Load sensors to under the device with ID 1001, naming each
# sensor "CPU"
$newSensors = Get-Sensor -Tags wmicpu* | Clone-Object -DestinationId 1001 "CPU"
# Clone all WMI CPU Load sensors to under the device with ID 1001, naming each
# sensor "CPU (<deviceName>)"
$newSensors = Get-Sensor -Tags wmicpu* | foreach {
    $_ | Clone-Object -DestinationId 1001 "CPU ($($_.Device))"
}
# Clone the device with ID 1000 into the group or probe with ID 2001 naming the
# device "dc-2" and setting its hostname to "dc-2.contoso.local"
$newDevice = Get-Device -Id 1000 | Clone-Object -DestinationId 2001 "dc-2" "dc-2.contoso.local"

If a host is not specified for a device, PrtgAPI will automatically use the Host property of the input object.

Note: upon resuming a cloned device, PRTG may automatically perform an auto-discovery of the cloned device depending on the auto-discovery mode of the device. This property can be modified in bulk by setting the AutoDiscoveryMode property to Manual. For more information, see Property Manipulation.

For scenarios in which you simply wish to copy a NotificationTrigger from one object to another, the Clone-Object cmdlet provides a convenience parameter set to save you from first having to wrap the trigger up in a set of TriggerParameters then add the trigger to the new object

# Copy all triggers from the contoso probe to the object with ID 5678
Get-Probe contoso | Get-Trigger | Clone-Object -DestinationId 5678

Clone To

In Clone To mode, a single sensor, device or group is cloned to one or more probes, groups or devices.

# Clone the sensor with ID 2002 to all of your Exchange Servers
Get-Device *exch* | Clone-Object -SourceId 2002

When operating in Clone To mode, you'll typically be cloning your source object similar to those you'll be cloning to (i.e. you created a sensor on one Exchange Server, now want to copy it to all the others). To avoid creating duplicate sensors, you should filter out the parent of the object you're cloning from

# Clone the sensor with ID 2002 from the Exchange Server named exch-1
Get-Device *exch* | where name -ne exch-1 | Clone-Object -SourceId 2002

PrtgAPI will validate that the specified object ID refers to a valid sensor, device or group, however will not validate that the specified object ID is a valid child for the specified parent. Attempting to clone an object into an invalid parent (such as cloning a group into a device) will generate an error from PRTG, resulting in a PrtgRequestException

Object Resolution

When an object has been cloned, by default it will be paused, requiring the object be unpaused either via the PRTG UI or via a call to Resume-Object. As such, Clone-Object will automatically attempt to resolve the object ID of the object created by PRTG into its resultant object that would typically be returned from either Get-Sensor, Get-Device or Get-Probe to use in further processing.

Depending on the speed of your PRTG install, it may take several seconds for the object to be fully created. In the event the object is not created by the time PrtgAPI asks for it, PrtgAPI will send a message to the PowerShell Warning Stream indicating the request failed, as well as the number of further attempts it will make to resolve the object (up to a maximum of 4). PrtgAPI will double the time it waits between each successive retry to give PRTG a chance to fully complete the object. Object resolution can be cancelled at any time by pressing Ctrl+C on your keyboard.

If you wish to disable object resolution, you can specify -Resolve:$false. This will cause PrtgAPI to provide a general overview of the cloned object using the information already available to it.

C:\> Get-Sensor -Id 1001 | Clone-Object -DestinationId 2001 "New Sensor" -Resolve:$false

Id    Name
--    ----
3001  New Sensor

If you wish to suppress the warning message, this can be achieved by specifying -WarningAction SilentlyContinue

Auto-Discovery

Auto-discovery operations can be batch initiated on devices using the Start-AutoDiscovery cmdlet.

# Start an auto-discovery operation on every device in your PRTG Server (don't do this)
Get-Device | Start-AutoDiscovery

Auto-discoveries can be limited in scope to one or more device templates. Device templates can either be specified as one or more search expressions

Get-Device -Id 2041 | Start-AutoDiscovery *wmi*,*rdp*

Or as one or more DeviceTemplate objects returned by the Get-DeviceTemplate cmdlet

$templates = Get-DeviceTemplate *wmi*,*rdp*

Get-Device -Id 2041 | Start-AutoDiscovery $templates

Depending on the size of your PRTG installation, auto-discovery operations can cause significant performance issues on your core server. As such care should be taken when programmatically initiating multiple auto-discovery operations. PRTG will only execute a maximum of 10 auto-discovery operations at once. If more than 10 auto-discovery operations are requested, PRTG will queue all operations and initiate them as slots become available.

The Start-AutoDiscovery cmdlet is capable of executing in PassThru Mode. For more information on PassThru Mode, see PassThru Requests.

See Also

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.