lordmilko / PrtgAPI

C#/PowerShell interface for PRTG Network Monitor
MIT License
301 stars 37 forks source link

STRANGE UPDATE WITH A POWERSHELL SCRIPT #235

Closed WilLabisoumaniac closed 3 years ago

WilLabisoumaniac commented 3 years ago

Hi,

I launch this powershell script :

$ListFiltre = get-device Exp write-host $ListFiltre

foreach ($Device in $ListFiltre) {
$Name = get-device $Device | Get-ObjectProperty -RawProperty name_ if ($Name.Length -ne 0) { $Name = $Name.SubString(4)

write-host $Name

    get-device $Device | set-ObjectProperty name $Name   
}    

}

But after the end, when i go to PRTG, on somes group your api put this : System.Object[] on device name instead of the real device name, do you now why ? PRTG

Thanks.

Wilfrid

lordmilko commented 3 years ago

Hi @WilLabisoumaniac,

There are a few issues I can see in your script

First, we have three redundant invocations of Get-Device

$ListFiltre = get-device Exp
foreach ($Device in $ListFiltre)
{
$Name = get-device $Device | Get-ObjectProperty -RawProperty name_
get-device $Device | set-ObjectProperty name $Name

Suppose you have two devices in your PRTG installation called "dc-1", and use that in place of the expression Exp

$ListFiltre = get-device dc-1

You then proceed to loop over these devices one by one. However, when you then do this

foreach ($Device in $ListFiltre)
{
$Name = get-device $Device | ...

This is going to retrieve all devices called dc-1 again. Not only is this redundant (because you already have all the Device objects for the devices called dc-1) but its also problematic, because if you have multiple devices called dc-1 you're now going to have an array of devices, which defeats the purpose of doing the foreach loop. When you pipe these devices into Get-ObjectProperty, this becomes an array of strings. This is why your devices are sometimes being called System.Object[]

Then, you do this

Get-ObjectProperty -RawProperty name_

This is redundant too; devices already have a Name property, there should be no reason to retrieve the name again via Get-ObjectProperty.

Finally, you then do

get-device $Device | set-ObjectProperty name $Name

Again, as described above this is redundant (you already have a Device object) and also problematic (what if there are two devices called dc-1)

Given it should be impossible to have a device whose name is empty, you should be able to remove the first 4 characters from every devices name by doing

Get-Devoce dc-1 | foreach { $_ | Set-ObjectProperty Name $_.Name.Substring(4) }
WilLabisoumaniac commented 3 years ago

Many thanks :)