Code Snippets Library
This library contains practical code snippets and examples for common LogicMonitor automation tasks. Each snippet includes detailed examples and the full source code for reference.
Bulk Import Operations
Import Devices from CSV
This function helps automate the process of importing multiple devices into LogicMonitor using a CSV file. It’s particularly useful when migrating devices from another system or performing bulk device additions. The function supports custom properties, group creation/assignments, and collector configurations.
# Generate a sample CSV templateImport-LMDevicesFromCSV -GenerateExampleCSV
# Import devices from CSV with specific collectorImport-LMDevicesFromCSV -FilePath "devices.csv" -CollectorId 1 -PassThru
# Import devices with auto-balanced collector groupImport-LMDevicesFromCSV -FilePath "devices.csv" -AutoBalancedCollectorGroupId 2
View Function Source
Function Import-LMDevicesFromCSV { [CmdletBinding(DefaultParameterSetName="Import")] param ( [Parameter(Mandatory=$true, ParameterSetName="Import")] [ValidateScript({Test-Path $_})] [String]$FilePath,
[Parameter(ParameterSetName="Sample")] [Switch]$GenerateExampleCSV,
[Parameter(ParameterSetName="Import")] [Switch]$PassThru,
[Parameter(ParameterSetName="Import")] [Nullable[Int]]$CollectorId,
[Parameter(ParameterSetName="Import")] [Nullable[Int]]$AutoBalancedCollectorGroupId
) #Check if we are logged in and have valid api creds Begin { $Results = New-Object System.Collections.ArrayList } Process { If($GenerateExampleCSV){ $SampleCSV = ("ip,displayname,hostgroup,collectorid,abcgid,description,snmp.community,property.name1,property.name2").Split(",")
[PSCustomObject]@{ $SampleCSV[0]="192.168.1.1" $SampleCSV[1]="SampleDeviceName" $SampleCSV[2]="Full/Path/To/Resource" $SampleCSV[3]="0" $SampleCSV[4]="$null" $SampleCSV[5]="My sample device" $SampleCSV[6]="public" $SampleCSV[7]="property value 1" $SampleCSV[8]="property value 2" } | Export-Csv "SampleLMDeviceImportCSV.csv" -Force -NoTypeInformation
Write-Host "[INFO]: Saved sample CSV (SampleLMDeviceImportCSV.csv) to current directory."
Return } If ($(Get-LMAccountStatus).Valid) { $DeviceList = Import-Csv -Path $FilePath
If($DeviceList){ #Get property headers for adding to property hashtable $PropertyHeaders = ($DeviceList | Get-Member -MemberType NoteProperty).Name | Where-Object {$_ -notmatch "ip|displayname|hostgroup|collectorid|abcgid|description"}
$i = 1 $DeviceCount = ($DeviceList | Measure-Object).Count
#Loop through device list and add to portal Foreach($Device in $DeviceList){ Write-Progress -Activity "Processing Device Import: $($Device.displayname)" -Status "$([Math]::Floor($($i/$DeviceCount*100)))% Completed" -PercentComplete $($i/$DeviceCount*100) -Id 0 $Properties = @{} Foreach($Property in $PropertyHeaders){ If($null -ne $Device."$Property"){$Properties.Add($Property,$Device."$Property")} } Try{ $CurrentGroup = $Device.hostgroup.Replace("\","/") #Replace backslashes with forward slashes for LM API $GroupId = (Get-LMDeviceGroup | Where-Object {$_.fullpath -eq $CurrentGroup}).Id If(!$GroupId){ $GroupPaths = $Device.hostgroup.Split("/") $j = 1 $GroupPathsCount = ($GroupPaths | Measure-Object).Count Foreach($Path in $GroupPaths){ Write-Progress -Activity "Processing Group Creation: $CurrentGroup" -Status "$([Math]::Floor($($j/$GroupPathsCount*100)))% Completed" -PercentComplete $($j/$GroupPathsCount*100) -ParentId 0 -Id 1 $GroupId = New-LMDeviceGroupFromPath -Path $Path -PreviousGroupId $GroupId $j++ } }
#Parameter takes precedence over csv value If(!$CollectorId){$SetCollectorId = $Device.collectorid}Else{$SetCollectorId = $CollectorId}
#Parameter takes precedence over csv value If(!$AutoBalancedCollectorGroupId){$SetAutoBalancedCollectorGroupId = $Device.abcgid}Else{$SetAutoBalancedCollectorGroupId = $AutoBalancedCollectorGroupId}
If($null -eq $SetCollectorId){ Write-Error "[ERROR]: CollectorId is required for device import, please ensure you have a valid collector id in your csv file." Break }
$DeviceParams = @{ Name = $Device.ip DisplayName = $Device.displayname Description = $Device.description PreferredCollectorId = $SetCollectorId AutoBalancedCollectorGroupId = $SetAutoBalancedCollectorGroupId HostGroupIds = $GroupId Properties = $Properties ErrorAction = "Stop" }
#Remove empty values from hashtable @($DeviceParams.keys) | ForEach-Object { if ([string]::IsNullOrEmpty($DeviceParams[$_])) { $DeviceParams.Remove($_) } }
$Device = New-LMDevice @DeviceParams $Results.Add($Device) | Out-Null $i++ } Catch{ Write-Error "[ERROR]: Unable to add device $($Device.displayname) to portal: $_" } } } } Else { Write-Error "Please ensure you are logged in before running any commands, use Connect-LMAccount to login and try again." } } End { Return $(If($PassThru){$Results}Else{$Null}) }}
Sample CSV format:
ip,displayname,hostgroup,collectorid,abcgid,description,snmp.community,property.name1,property.name2192.168.1.1,SampleDeviceName,Full/Path/To/Resource,0,,My sample device,public,property value 1,property value 2
Import Device Groups from CSV
Automates the creation of device groups and their hierarchies using a CSV file. This is useful for setting up initial group structures or reorganizing existing groups. The function handles nested group creation, applies to rules, and custom properties.
# Generate a sample CSV templateImport-LMDeviceGroupsFromCSV -GenerateExampleCSV
# Import device groups from CSVImport-LMDeviceGroupsFromCSV -FilePath "groups.csv" -PassThru
View Function Source
Function Import-LMDeviceGroupsFromCSV { [CmdletBinding(DefaultParameterSetName="Import")] param ( [Parameter(Mandatory=$true, ParameterSetName="Import")] [ValidateScript({Test-Path $_})] [String]$FilePath,
[Parameter(ParameterSetName="Sample")] [Switch]$GenerateExampleCSV,
[Parameter(ParameterSetName="Import")] [Switch]$PassThru )
#Check if we are logged in and have valid api creds Begin { $Results = New-Object System.Collections.ArrayList } Process { If($GenerateExampleCSV){ $SampleCSV = ("name,fullpath,description,appliesTo,property.name1,property.name2").Split(",")
$SampleContent = New-Object System.Collections.ArrayList $SampleContent.Add([PSCustomObject]@{ $SampleCSV[0]="California" $SampleCSV[1]="Locations/North America" $SampleCSV[2]="My sample device group for CA" $SampleCSV[3]='system.displayName =~ "CA-*" && isDevice()' $SampleCSV[4]="property value 1" $SampleCSV[5]="property value 2" }) | Out-Null $SampleContent.Add([PSCustomObject]@{ $SampleCSV[0]="New York" $SampleCSV[1]="Locations/North America" $SampleCSV[2]="My sample device group for NY" $SampleCSV[3]='system.displayName =~ "NY-*" && isDevice()' $SampleCSV[4]="property value 1" $SampleCSV[5]="property value 2" }) | Out-Null $SampleContent.Add([PSCustomObject]@{ $SampleCSV[0]="London" $SampleCSV[1]="Locations/Europe" $SampleCSV[2]="My sample device group for London" $SampleCSV[3]='system.displayName =~ "LONDON-*" && isDevice()' $SampleCSV[4]="property value 1" $SampleCSV[5]="property value 2" }) | Out-Null
$SampleContent | Export-Csv "SampleLMDeviceGroupImportCSV.csv" -Force -NoTypeInformation
Return } If ($(Get-LMAccountStatus).Valid) { $GroupList = Import-Csv -Path $FilePath
If($GroupList){ #Get property headers for adding to property hashtable $PropertyHeaders = ($GroupList | Get-Member -MemberType NoteProperty).Name | Where-Object {$_ -notmatch "name|fullpath|description|appliesTo"}
$i = 1 $GroupCount = ($GroupList | Measure-Object).Count
#Loop through device list and add to portal Foreach($DeviceGroup in $GroupList){ Write-Progress -Activity "Processing Group Import: $($DeviceGroup.name)" -Status "$([Math]::Floor($($i/$GroupCount*100)))% Completed" -PercentComplete $($i/$GroupCount*100) -Id 0 $Properties = @{} Foreach($Property in $PropertyHeaders){ $Properties.Add($Property,$DeviceGroup."$Property") } Try{ $CurrentGroup = $DeviceGroup.fullpath.Replace("\","/") #Replace backslashes with forward slashes for LM API $GroupId = (Get-LMDeviceGroup | Where-Object {$_.fullpath -eq $CurrentGroup}).Id If(!$GroupId){ $GroupPaths = $DeviceGroup.fullpath.Split("/") $j = 1 $GroupPathsCount = ($GroupPaths | Measure-Object).Count Foreach($Path in $GroupPaths){ Write-Progress -Activity "Processing Parent Group Creation: $CurrentGroup" -Status "$([Math]::Floor($($j/$GroupPathsCount*100)))% Completed" -PercentComplete $($j/$GroupPathsCount*100) -ParentId 0 -Id 1 $GroupId = New-LMDeviceGroupFromPath -Path $Path -PreviousGroupId $GroupId $j++ } } $DeviceGroup = New-LMDeviceGroup -name $DeviceGroup.name -Description $DeviceGroup.description -ParentGroupId $GroupId -Properties $Properties -AppliesTo $DeviceGroup.appliesTo -ErrorAction Stop $Results.Add($DeviceGroup) | Out-Null $i++ } Catch{ Write-Error "[ERROR]: Unable to add device $($DeviceGroup.name) to portal: $_" } } } } Else { Write-Error "Please ensure you are logged in before running any commands, use Connect-LMAccount to login and try again." } } End { Return $(If($PassThru){$Results}Else{$Null}) }}
Sample CSV format:
name,fullpath,description,appliesTo,property.name1,property.name2California,Locations/North America,My sample device group for CA,system.displayName =~ "CA-*" && isDevice(),property value 1,property value 2
Device Management
Deduplicate Devices
Helps identify and remove duplicate devices in your LogicMonitor portal. Duplicates are detected based on system properties like hostname, IP addresses, and system names. This is particularly useful after migrations or when multiple collectors discover the same devices.
# List potential duplicate devicesInvoke-LMDeviceDedupe -ListDuplicates -DeviceGroupId 8
# Remove duplicate devicesInvoke-LMDeviceDedupe -RemoveDuplicates -DeviceGroupId 8
# Exclude specific IPs or device types from deduplicationInvoke-LMDeviceDedupe -ListDuplicates -IpExclusionList @("10.0.0.1","10.0.0.2") -ExcludeDeviceType @(8,9)
View Function Source
Function Invoke-LMDeviceDedupe {
[CmdletBinding()] Param ( [Parameter(ParameterSetName = 'List',Mandatory)] [Switch]$ListDuplicates,
[Parameter(ParameterSetName = 'Remove',Mandatory)] [Switch]$RemoveDuplicates,
[String]$DeviceGroupId,
[String[]]$IpExclusionList,
[String[]]$SysNameExclusionList,
[String[]]$ExcludeDeviceType = @(8) #Exclude K8s resources by default ) #Check if we are logged in and have valid api creds Begin {} Process { If ($(Get-LMAccountStatus).Valid) { $DeviceList = @()
$IpExclusionList += @("127.0.0.1","::1")
$SysNameExclusionList += @("(none)","N/A","none","blank","empty","")
If($DeviceGroupId){ $DeviceList = Get-LMDeviceGroupDevices -Id $DeviceGroupId } Else{ $DeviceList = Get-LMDevice }
#Remove excluded device types $DeviceList = $DeviceList | Where-Object {$ExcludeDeviceType -notcontains $_.deviceType}
If($DeviceList){ $OrganizedDevicesList = @() $DuplicateSysNameList = @() $RemainingDeviceList = @()
$OutputList = @()
#Loop through list and compare sysname, hostname and ips Foreach($Device in $DeviceList){ $IpList = $null $IpListIndex = $Device.systemProperties.name.IndexOf("system.ips") If($IpListIndex -ne -1){ $IpList = $Device.systemProperties[$IpListIndex].value }
$SysName = $null $SysNameIndex = $Device.systemProperties.name.IndexOf("system.sysname") If($SysNameIndex -ne -1){ $SysName = $Device.systemProperties[$SysNameIndex].value.tolower() }
$HostName = $null $HostNameIndex = $Device.systemProperties.name.IndexOf("system.hostname") If($HostNameIndex -ne -1){ $HostName = $Device.systemProperties[$HostNameIndex].value.tolower() }
$OrganizedDevicesList += [PSCustomObject]@{ ipList = $IpList sysName = $SysName hostName = $HostName displayName = $Device.displayName deviceId = $Device.id currentCollectorId = $Device.currentCollectorId createdOnEpoch = $Device.createdOn createdOnDate = (Get-Date 01.01.1970)+([System.TimeSpan]::fromseconds($($Device.createdOn))) } } #Remove items that are missing system.ips and system.sysname $OrganizedDevicesList = $OrganizedDevicesList | ? {$_.ipList -ne $null -or $_.sysName -ne $null}
#group devices with matching sysname values $DuplicateSysNameList = $OrganizedDevicesList | Group-Object -Property sysname | Sort-Object Count -Unique -Descending | ? {$_.Count -gt 1 -and $SysNameExclusionList -notcontains $_.Name}
#Group remaining devices into array so we can process for duplicate ips $RemainingDeviceList = ($OrganizedDevicesList | Group-Object -Property sysname | Sort-Object Count -Unique -Descending | ? {$_.Count -eq 1 -or $SysNameExclusionList -contains $_.Name}).Group
#Loop through each group and add duplicates to our list Foreach($Group in $DuplicateSysNameList){ #Get the oldest device out of the group and mark as original device to keep around $OriginalDeviceEpochIndex = $Group.Group.createdOnEpoch.IndexOf($($Group.Group.createdOnEpoch | sort-object -Descending | Select -last 1)) $OriginalDevice = $Group.Group[$OriginalDeviceEpochIndex] Foreach($Device in $Group.Group){ If($Device.deviceId -ne $OriginalDevice.deviceId){ $OutputList += [PSCustomObject]@{ duplicate_deviceId = $Device.deviceId duplicate_sysName = $Device.sysName duplicate_hostName = $Device.hostName duplicate_displayName = $Device.displayName duplicate_currentCollectorId = $Device.currentCollectorId duplicate_createdOnEpoch = $Device.createdOnEpoch duplicate_createdOnDate = $Device.createdOnDate duplicate_ipList = $Device.ipList original_deviceId = $OriginalDevice.deviceId original_sysName = $OriginalDevice.sysName original_hostName = $OriginalDevice.hostName original_displayName = $OriginalDevice.displayName original_currentCollectorId = $OriginalDevice.currentCollectorId original_createdOnEpoch = $OriginalDevice.createdOnEpoch original_createdOnDate = $OriginalDevice.createdOnDate original_ipList = $OriginalDevice.ipList duplicate_reason = "device is considered a duplicate for having a matching sysname value of $($Device.sysName) with $($Group.Count) devices" } } } }
$DuplicateIPDeviceList = @() $DuplicateIPDeviceGroupList = @()
#Find duplicate ips for use to locate $DuplicateIPList = @() $DuplicateIPList = ($RemainingDeviceList.iplist.split(",") | Group-Object | ?{ $_.Count -gt 1 -and $IpExclusionList -notcontains $_.Name}).Group | Select-Object -Unique
If($DuplicateIPList){ Foreach($Device in $RemainingDeviceList){ #TODO process system.ips list for dupes if assigned to same collector id $DuplicateCheckResult = @() $DuplicateCheckResult = Compare-Object -ReferenceObject $DuplicateIpList -DifferenceObject $($Device.ipList).split(",") -IncludeEqual -ExcludeDifferent -PassThru If($DuplicateCheckResult){ $DuplicateIPDeviceList += [PSCustomObject]@{ deviceId = $Device.deviceId ipList = $Device.ipList sysName = $Device.sysName hostName = $Device.hostName displayName = $Device.displayName currentCollectorId = $Device.currentCollectorId createdOnEpoch = $Device.createdOnEpoch createdOnDate = $Device.createdOnDate duplicate_ips = $DuplicateCheckResult -join "," } } } }
#Group devices with the same duplicate IPs so we can add them to our group $DuplicateIPDeviceGroupList = $DuplicateIPDeviceList | Group-Object -Property duplicate_ips | Sort-Object Count -Unique -Descending | ? {$_.count -gt 1} Foreach($Group in $DuplicateIPDeviceGroupList){ #Get the oldest device out of the group and mark as original device to keep around $OriginalDeviceEpochIndex = $Group.Group.createdOnEpoch.IndexOf($($Group.Group.createdOnEpoch | sort-object -Descending | Select -last 1)) $OriginalDevice = $Group.Group[$OriginalDeviceEpochIndex] Foreach($Device in $Group.Group){ If($Device.deviceId -ne $OriginalDevice.deviceId){ $OutputList += [PSCustomObject]@{ duplicate_deviceId = $Device.deviceId duplicate_sysName = $Device.sysName duplicate_hostName = $Device.hostName duplicate_displayName = $Device.displayName duplicate_currentCollectorId = $Device.currentCollectorId duplicate_createdOnEpoch = $Device.createdOnEpoch duplicate_createdOnDate = $Device.createdOnDate duplicate_ipList = $Device.ipList original_deviceId = $OriginalDevice.deviceId original_sysName = $OriginalDevice.sysName original_hostName = $OriginalDevice.hostName original_displayName = $OriginalDevice.displayName original_currentCollectorId = $OriginalDevice.currentCollectorId original_createdOnEpoch = $OriginalDevice.createdOnEpoch original_createdOnDate = $OriginalDevice.createdOnDate original_ipList = $OriginalDevice.ipList duplicate_reason = "device is considered a duplicate for having a matching system.ips value of $($Device.duplicate_ips) with $($Group.Count) devices" } } } } If($OutputList){ If($ListDuplicates){ Return (Add-ObjectTypeInfo -InputObject $OutputList -TypeName "LogicMonitor.DedupeList" ) } ElseIf($RemoveDuplicates){ Foreach($Device in $OutputList){ #Remove duplicate devices Write-Host "Removing device ($($Device.duplicate_deviceId)) $($Device.duplicate_displayName) for reason: $($Device.duplicate_reason)" Remove-LMDevice -Id $Device.duplicate_deviceId } } } Else{ Write-Host "No duplicates detected based on set parameters." } } } Else { Write-Error "Please ensure you are logged in before running any commands, use Connect-LMAccount to login and try again." } } End {}}
Add Device to Group
Simplifies the process of adding devices to groups while preserving existing group memberships. This is useful for organizing devices into multiple logical groups without disrupting existing group assignments.
# Add device to group by nameAdd-LMDeviceToGroup -Id 123 -GroupName "Production Servers"
# Add device to group by ID with confirmation of changesAdd-LMDeviceToGroup -Id 123 -GroupId 456 -PassThru
# Add multiple devices to a groupGet-LMDevice -Filter 'displayName -contains "web"' | Add-LMDeviceToGroup -GroupName "Web Servers"
View Function Source
Function Add-LMDeviceToGroup{ [CmdletBinding()] Param( [Parameter(Mandatory,ValueFromPipelineByPropertyName)] [String]$Id,
[Parameter(Mandatory,ParameterSetName = "GroupName")] [String]$GroupName,
[Parameter(Mandatory,ParameterSetName = "GroupId")] [String]$GroupId,
[Switch]$PassThru ) Begin{ If($(Get-LMAccountStatus).Valid){}Else{Write-Error "Please ensure you are logged in before running any commands, use Connect-LMAccount to login and try again.";return} } Process{
#Get the device $Device = Get-LMDevice -Id $Id
If($Device){ #Get the device group id If($GroupName){ $GroupId = (Get-LMDeviceGroup -Name $GroupName).id
If($($GroupId | Measure-Object).Count -gt 1){ Write-Error "Multiple device groups found for the specified name value: $GroupName. Please ensure value is unique and try again" Return } }
#Join the device group ids $HostGroupIds = $Device.HostGroupIds + "," + $GroupId #Add the device to the group
Write-Host "Adding device $($Device.Name) to group $($GroupId)" $Result = Set-LMDevice -Id $Id -HostGroupIds $HostGroupIds
#Return the result If($PassThru){ $Result } } Else{ Write-Error "Device $($Id) not found" } } End{}}
Copy Device Properties to Groups
Enables copying properties from a source device to one or more device groups. This is useful for standardizing properties across groups or propagating configuration templates from reference devices.
# Copy specific properties from a device to groupsCopy-LMDevicePropertyToGroup -SourceDeviceId 123 -TargetGroupId 456,457 -PropertyNames "location","department"
# Copy properties from random device in source groupCopy-LMDevicePropertyToGroup -SourceGroupId 789 -TargetGroupId 456 -PropertyNames "location" -PassThru
# Copy multiple properties to multiple groups$props = @("location", "environment", "team")$targetGroups = @(456, 457, 458)Copy-LMDevicePropertyToGroup -SourceDeviceId 123 -TargetGroupId $targetGroups -PropertyNames $props
View Function Source
Function Copy-LMDevicePropertyToGroup { [CmdletBinding(DefaultParameterSetName="SourceDevice")] Param( [Parameter(Mandatory,ParameterSetName="SourceDevice",ValueFromPipelineByPropertyName)] [String]$SourceDeviceId,
[Parameter(Mandatory,ParameterSetName="SourceGroup")] [String]$SourceGroupId,
[Parameter(Mandatory)] [String[]]$TargetGroupId,
[Parameter(Mandatory)] [String[]]$PropertyNames,
[Switch]$PassThru )
Begin { If($(Get-LMAccountStatus).Valid){} Else{ Write-Error "Please ensure you are logged in before running any commands, use Connect-LMAccount to login and try again." return } }
Process { Try { # Get source device either directly or from group If($PSCmdlet.ParameterSetName -eq "SourceDevice") { $sourceDevice = Get-LMDevice -Id $SourceDeviceId If(!$sourceDevice) { Write-Error "Source device with ID $SourceDeviceId not found" return } } Else { $devices = Get-LMDeviceGroupDevices -Id $SourceGroupId If(!$devices) { Write-Error "No devices found in source group with ID $SourceGroupId" return } $sourceDevice = $devices | Get-Random }
# Initialize results array if PassThru specified $results = New-Object System.Collections.ArrayList
# Process each target group Foreach($groupId in $TargetGroupId) { $group = Get-LMDeviceGroup -Id $groupId If(!$group) { Write-Warning "Target group with ID $groupId not found, skipping..." continue }
# Build properties hashtable $propertiesToCopy = @{} Foreach($propName in $PropertyNames) { # Check custom properties $propValue = $null If($sourceDevice.customProperties.name -contains $propName) { $propValue = $sourceDevice.customProperties[$sourceDevice.customProperties.name.IndexOf($propName)].value } If($propValue) { $propertiesToCopy[$propName] = $propValue } Else { Write-Warning "Property $propName not found on source device $($sourceDevice.id), skipping..." } }
If($propertiesToCopy.Count -gt 0) { Write-Host "Copying properties to group $($group.name) (ID: $groupId)" $updatedGroup = Set-LMDeviceGroup -Id $groupId -Properties $propertiesToCopy If($PassThru) { $results.Add($updatedGroup) | Out-Null } } } } Catch { Write-Error "Error copying properties: $_" } }
End { If($PassThru) { Return $results } }}
Dashboard Management
Find Dashboard Widgets
Helps locate dashboard widgets that use specific datasources. This is particularly useful when updating datasources or identifying dependencies before making changes to LogicModules.
# Find widgets using specific datasourcesFind-LMDashboardWidgets -DatasourceNames "SNMP_Network_Interfaces"
# Search multiple datasources$datasources = @( "SNMP_Network_Interfaces", "VMware_vCenter_VM_Performance")Find-LMDashboardWidgets -DatasourceNames $datasources
# Search in specific dashboard group pathFind-LMDashboardWidgets -DatasourceNames "Windows_Performance" -GroupPathSearchString "*/Production/*"
# Pipe datasource names"SNMP_Network_Interfaces","Windows_Performance" | Find-LMDashboardWidgets
View Function Source
Function Find-LMDashboardWidgets{ Param( [Parameter(Mandatory,ValueFromPipeline)] [Alias("DatasourceName")] [String[]]$DatasourceNames,
[String]$GroupPathSearchString = "*" )
#Check if we are logged in and have valid api creds Begin {} Process { If ($(Get-LMAccountStatus).Valid) { $Results = New-Object System.Collections.ArrayList $Dashboards = Get-LMDashboard | Where-Object {$_.groupFullPath -like "$GroupPathSearchString"}
$i = 0 $DashCount = ($Dashboards | Measure-Object).Count Foreach($Dashboard in $Dashboards){ Write-Progress -Activity "Processing Dashboard: $($Dashboard.name)" -Status "$([Math]::Floor($($i/$DashCount*100)))% Completed" -PercentComplete $($i/$DashCount*100) -Id 0 $Widgets = Get-LMDashboardWidget -DashboardId $Dashboard.Id
$GraphWidgets = $Widgets | Where-Object {$_.type -eq "cgraph"} If($GraphWidgets.graphInfo.datapoints.dataSourceFullName){$GraphWidgetsFiltered = $GraphWidgets.graphInfo.datapoints | Where-Object {$DatasourceNames -contains $_.dataSourceFullName.Split("(")[-1].Replace(")","")}}
$BigNumberWidgets = $Widgets | Where-Object {$_.type -eq "bigNumber"} If($BigNumberWidgets.bigNumberInfo.dataPoints.dataSourceFullName){$BigNumberWidgetsFiltered = $BigNumberWidgets.bigNumberInfo.dataPoints | Where-Object {$DatasourceNames -contains $_.dataSourceFullName.Split("(")[-1].Replace(")","")}}
$PieWidgets = $Widgets | Where-Object {$_.type -eq "pieChart"} If($PieWidgets.pieChartInfo.dataPoints.dataSourceFullName){$PieWidgetsFiltered = $PieWidgets.pieChartInfo.dataPoints | Where-Object {$DatasourceNames -contains $_.dataSourceFullName.Split("(")[-1].Replace(")","")}}
$TableWidgets = $Widgets | Where-Object {$_.type -eq "dynamicTable"} If($TableWidgets.dataSourceFullName){$TableWidgetsFiltered = $TableWidgets | Where-Object {$DatasourceNames -contains $_.dataSourceFullName.Split("(")[-1].Replace(")","")}}
$SLAWidgets = $Widgets | Where-Object {$_.type -eq "deviceSLA"} If($SLAWidgets.metrics.dataSourceFullName){$SLAWidgetsFiltered = $SLAWidgets.metrics | Where-Object {$DatasourceNames -contains $_.dataSourceFullName.Split("(")[-1].Replace(")","")}}
$NOCWidgets = $Widgets | Where-Object {$_.type -eq "noc"} If($NOCWidgets.items.dataSourceDisplayName){$NOCWidgetsFiltered = $NOCWidgets.items | Where-Object {$DatasourceNames -contains $_.dataSourceDisplayName.Replace("\","")}}
$GaugeWidgets = $Widgets | Where-Object {$_.type -eq "gauge"} If($GaugeWidgets.dataPoint.dataSourceFullName){$GaugeWidgetsFiltered = $GaugeWidgets.dataPoint | Where-Object {$DatasourceNames -contains $_.dataSourceFullName.Split("(")[-1].Replace(")","")}}
If($GraphWidgetsFiltered){ $GraphWidgetsFiltered | ForEach-Object {$RefObj = $_ ;$Results.Add([PSCustomObject]@{ dataSourceId = $_.dataSourceId dataSourceFullName = $_.dataSourceFullName dataPointId = $_.dataPointId dataPointName = $_.dataPointName widgetType = "cgraph" widgetId = ($GraphWidgets | Where-Object {$_.graphInfo.datapoints -eq $RefObj}).Id widgetName = ($GraphWidgets | Where-Object {$_.graphInfo.datapoints -eq $RefObj}).Name dashboardId = $Dashboard.id dashboardName = $Dashboard.name dashboardPath = $Dashboard.groupFullPath }) | Out-Null} }
If($BigNumberWidgetsFiltered){ $BigNumberWidgetsFiltered | ForEach-Object {$RefObj = $_ ;$Results.Add([PSCustomObject]@{ dataSourceId = $_.dataSourceId dataSourceFullName = $_.dataSourceFullName dataPointId = $_.dataPointId dataPointName = $_.dataPointName widgetType = "bigNumber" widgetId = ($BigNumberWidgets | Where-Object {$_.bigNumberInfo.dataPoints -eq $RefObj}).Id widgetName = ($BigNumberWidgets | Where-Object {$_.bigNumberInfo.dataPoints -eq $RefObj}).Name dashboardId = $Dashboard.id dashboardName = $Dashboard.name dashboardPath = $Dashboard.groupFullPath }) | Out-Null} }
If($PieWidgetsFiltered){ $PieWidgetsFiltered | ForEach-Object {$RefObj = $_ ;$Results.Add([PSCustomObject]@{ dataSourceId = $_.dataSourceId dataSourceFullName = $_.dataSourceFullName dataPointId = $_.dataPointId dataPointName = $_.dataPointName widgetType = "pieChart" widgetId = ($PieWidgets | Where-Object {$_.pieChartInfo.dataPoints -eq $RefObj}).Id widgetName = ($PieWidgets | Where-Object {$_.pieChartInfo.dataPoints -eq $RefObj}).Name dashboardId = $Dashboard.id dashboardName = $Dashboard.name dashboardPath = $Dashboard.groupFullPath }) | Out-Null} }
If($TableWidgetsFiltered){ $TableWidgetsFiltered | ForEach-Object {$Results.Add([PSCustomObject]@{ dataSourceId = $_.dataSourceId dataSourceFullName = $_.dataSourceFullName dataPointId = "N/A" dataPointName = "N/A" widgetType = "dynamicTable" widgetId = $_.id widgetName = $_.name dashboardId = $Dashboard.id dashboardName = $Dashboard.name dashboardPath = $Dashboard.groupFullPath }) | Out-Null} }
If($SLAWidgetsFiltered){ $SLAWidgetsFiltered | ForEach-Object {$RefObj = $_ ;$Results.Add([PSCustomObject]@{ dataSourceId = $_.dataSourceId dataSourceFullName = $_.dataSourceFullName dataPointId = $_.dataPointId dataPointName = $_.dataPointName widgetType = "deviceSLA" widgetId = ($SLAWidgets | Where-Object {$_.metrics -eq $RefObj}).Id widgetName = ($SLAWidgets | Where-Object {$_.metrics -eq $RefObj}).Name dashboardId = $Dashboard.id dashboardName = $Dashboard.name dashboardPath = $Dashboard.groupFullPath }) | Out-Null} }
If($NOCWidgetsFiltered){ $NOCWidgetsFiltered | ForEach-Object {$RefObj = $_ ;$Results.Add([PSCustomObject]@{ dataSourceId = $_.dataSourceId dataSourceFullName = $_.dataSourceFullName dataPointId = $_.dataPointId dataPointName = $_.dataPointName widgetType = "noc" widgetId = ($NOCWidgets | Where-Object {$_.items -eq $RefObj}).Id widgetName = ($NOCWidgets | Where-Object {$_.items -eq $RefObj}).Name dashboardId = $Dashboard.id dashboardName = $Dashboard.name dashboardPath = $Dashboard.groupFullPath }) | Out-Null} }
If($GaugeWidgetsFiltered){ $GaugeWidgetsFiltered | ForEach-Object {$RefObj = $_ ;$Results.Add([PSCustomObject]@{ dataSourceId = $_.dataSourceId dataSourceFullName = $_.dataSourceFullName dataPointId = $_.dataPointId dataPointName = $_.dataPointName widgetType = "gauge" widgetId = ($GaugeWidgets | Where-Object {$_.dataPoint -eq $RefObj}).Id widgetName = ($GaugeWidgets | Where-Object {$_.dataPoint -eq $RefObj}).Name dashboardId = $Dashboard.id dashboardName = $Dashboard.name dashboardPath = $Dashboard.groupFullPath }) | Out-Null} } $i++ }
} Else { Write-Error "Please ensure you are logged in before running any commands, use Connect-LMAccount to login and try again." } } End { Return (Add-ObjectTypeInfo -InputObject $Results -TypeName "LogicMonitor.WidgetSearch" ) }}