#!/usr/bin/pwsh <# .SYNOPSIS Get Warranty Information directly from Dell via API. .DESCRIPTION An API Key is required to get access to the API. Register at: https://techdirect.dell.com/portal/AboutAPIs.aspx If "-OK" switch is used, expired warranty is alos okay .NOTES Author : Rafael Voss Version : V0.62b Based on : get-dellwarranty1.4.ps1 from https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Script-Get-21ffea36/view/Discussions License : MIT Prerequisite : PowerShell Core 6 or higher ToDo : HELP .EXAMPLE .\check_dell_warranty.ps1 -servicetag "AAABBB2" -apikey "aaa111aa-bbbb-aaaa-bb00-aaaaaaaaaaaaaa" -w 30 -c 12 #> Param( [switch]$debug, [switch]$help, [string]$servicetag, [string]$apikey, [Alias("O","Okay")] [switch]$ok, [int]$w = 30, [int]$c = 14 ) #hardcode Your key here (optional): #$apikey = "aaa111aa-bbbb-aaaa-bb00-aaaaaaaaaaaaaa" $countOK = 0 $countWarning = 0 $countCritical = 0 $platform = $PSVersionTable.Platform if ($platform -match "Unix" ) { #change env variables, otherwise Powercli will crash on module import $env:PWD="/var/lib/nagios" $env:HOME="/var/lib/nagios" } function main { if (!($servicetag -or $file) -or $help) { write-host "No ServiceTag or Servicetag file given!" write-host "Example for single host: check_DellWarranty.ps1 -ServiceTag `"1AA32AA`" -apikey "aaa111aa-bbbb-aaaa-bb00-aaaaaaaaaaaaaa" -w `"40`" -c `"10`"" write-host "Example for taglist: check_DellWarranty.ps1 -file `"c:\dell1ServiceTagperLine.txt`" -w `"40`" -c `"10`"" write-host "use -debug switch to see full output of Dell API result, if service was not found" write-host "default values for w/c: 30/14" exit 3 } if ($file) { $servicetag = get-content $file foreach ($st in $servicetag) { $warrentyInformation = Get-DellWarranty -ServiceTag $st -ApiKey $apikey -Dev $true $newestwarrenty = $warrentyInformation | where { ($_.Serviceleveldescription -match "support" -or $_.Serviceleveldescription -match "Onsite Service") } | sort-object Enddate -Descending | select -first 1 if (!( $newestwarrenty.Serviceleveldescription -match "support" -or $newestwarrenty.Serviceleveldescription -match "Onsite Service" )) { $newestwarrenty = $warrentyInformation | sort-object Enddate -Descending | select -first 1 write-host "No support found for $st ( Model: $($newestwarrenty.model) )!" if ($debug) { $warrentyInformation } $countCritical++ continue } #$warrantyEnddate = [datetime]::ParseExact($newestwarrenty.enddate,'yyyy-MM-ddTHH:mm:ss',$null) $warrantyEnddate = $newestwarrenty.enddate if ($warrentyEnddate -match "T") { $warrantyEnddate = [datetime]::ParseExact($newestwarrenty.enddate,'yyyy-MM-ddTHH:mm:ss',$null) } else { $warrantyEnddate = [datetime]$warrantyEnddate } $warrantyEnddateString = $warrantyEnddate.ToString("dd-MM-yyyy") #Generate Exitcodes and Output if ( $warrantyEnddate -gt (get-date).AddDays(-$w)) { $status = "OK:" $countOK++ } if ( $warrantyEnddate -lt (get-date).AddDays(-$w) -and $warrantyEnddate -gt (get-date).AddDays(-$c)) { $status = "WARNING:" $countWarning++ } if ( $warrantyEnddate -lt (get-date).AddDays(-$c)) { $status = "CRITICAL:" $countCritical++ } write-host "$status $((New-TimeSpan -End $warrantyEnddate).Days) days ($warrantyEnddateString) - Model: $($newestwarrenty.Model) - ServiceTag: $st - Support: `'$($newestwarrenty.ServiceLevelDescription)`'" } write-host "OK/Warn/Crit $countOK/$countWarn/$countCritical" if ($countCritical -gt 0) { if ($ok) { write-host "OK switch is used! So every Result is returning ok" exit 0 } else { exit 2 } } if ($countWarning -gt 0) { if ($ok) { write-host "OK switch is used! So every Result is returning ok" exit 0 } else { exit 2 } } if ($countWarning -eq 0 -and $countCritical -eq 0 -and $countOK -gt 0) { exit 0 } else { write-host "no Servicetags found. Something went wrong" exit 3 } } else { $warrentyInformation = Get-DellWarranty -ServiceTag $servicetag -ApiKey $apikey -Dev $true $newestwarrenty = $warrentyInformation | where { ($_.Serviceleveldescription -match "support" -or $_.Serviceleveldescription -match "Onsite Service") } | sort-object Enddate -Descending | select -first 1 if (!( $newestwarrenty.Serviceleveldescription -match "support" -or $newestwarrenty.Serviceleveldescription -match "Onsite Service" )) { $newestwarrenty = $warrentyInformation | sort-object Enddate -Descending | select -first 1 write-host "No support found for $servicetag ( Model: $($newestwarrenty.model) )!" if ($debug) { $warrentyInformation } $countCritical++ exit 3 } #$warrantyEnddate = [datetime]::ParseExact($newestwarrenty.enddate,'yyyy-MM-ddTHH:mm:ss',$null) $warrantyEnddate = $newestwarrenty.enddate if ($warrentyEnddate -match "T") { $warrantyEnddate = [datetime]::ParseExact($newestwarrenty.enddate,'yyyy-MM-ddTHH:mm:ss',$null) } else { $warrantyEnddate = [datetime]$warrantyEnddate } $warrantyEnddateString = $warrantyEnddate.ToString("dd-MM-yyyy") #Generate Exitcodes and Output if ( $warrantyEnddate -gt (get-date).AddDays(-$w)) { $exitcode = 0 $status = "OK:" } if ( $warrantyEnddate -lt (get-date).AddDays(-$w) -and $warrantyEnddate -gt (get-date).AddDays(-$c)) { $exitcode = 1 $status = "WARNING:" } if ( $warrantyEnddate -lt (get-date).AddDays(-$c)) { $exitcode = 2 $status = "CRITICAL:" } } $expresscode = Get-DellExpressServiceCode $servicetag -SkipSystemCheck write-host "$status Warranty expires in $((New-TimeSpan -End $warrantyEnddate).Days) days - $warrantyEnddateString" write-host "Model: $($newestwarrenty.Model) - ServiceTag: $servicetag/$expresscode - Support: `'$($newestwarrenty.ServiceLevelDescription)`'" if ($ok) { write-host "OK switch is used! So every Result is returning ok" exit 0 } else { exit $exitcode } } Function Get-DellWarranty { <# .SYNOPSIS Submits service tags to Dell's online database as sinlge queries or in groups. Returns a table of warranty entitlements for the specified tags. .DESCRIPTION Using Dell's online server supporting the REST API, this function can submit service tags and collect warranty entitlement information which will then be returned as a table. .PARAMETER ServiceTag Accepts a single Service Tag, comma separated list of tags, an array of tags from the pipeline, or pipeline input by property name. .PARAMETER ApiKey Accepts a string value for the API key. Defaults to the SJM API key. .PARAMETER Dev Switched parameter that specifies whether the function should use Dell sandbox server. Recommended for testing with other functions. Defaults to Production server. .PARAMETER TagLimit Specifies the maximum number of tags that should be submitted per query. Defaults to 25. .EXAMPLE Get-DellWarranty "1T34F72" Lists all entitlement types for the Service Tag "1T34F72". .EXAMPLE Get-SCCMComputer -ComputerModel "Latitude 7250" | Get-DellWarranty Sends output of Get-SCCMComputer down the pipeline to Get-DellWarranty and returns entitlements that match the specified Service Tags. .INPUTS .OUTPUTS .NOTES =========================================================================================== Created On: 09/09/2016 Updated On: 06/09/2017 Created By: Natascia Heil,Aaron Bauer Organization: SJM/Abbott FileName: Get-DellWarranty.ps1 Revision No: 1.4 Modifications: 1.0: Downloaded from https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Script-Get-Dell-d7fd6367 1.1: Changed some of the paramater options. Created a array internally to store all the returned properties and organize them in a table for return as an object. Included logic to handle NIL returns Included column in the table for including the date the script was run (extract date) 1.2: Updated parameter options to cast as an array to accept data from the pipeline. Doing a join internally for submitting multiple tags to Dell as a comma separated list Included variable to set max number of tags accepted and logic to respect that 1.3: Added pipeline support, aliases for the ServiceTag property, and Verbose messaging. Rearranged some of the logic to support Begin,Process,End. Added TagLimit paramter which defaults to 25. 1.4: Added comment based help. =========================================================================================== #> [CmdletBinding()] Param( [Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true, Mandatory=$true)] [Alias("Serial","SerialNumber")] [String]$ServiceTag , [Parameter(Mandatory=$false)] [String]$ApiKey = '' , [Parameter(Mandatory=$false)] [Switch]$Dev , [Parameter(Mandatory=$False)] [INT]$TagLimit = 25 )#Param Begin #Setup variables and define functions { $Script:Table = New-Object System.Collections.ArrayList #Create new array for organizing the data in the script scope so that it can be modified in the function $ServiceTags = New-Object System.Collections.ArrayList If (($Dev)) { $Server = "https://sandbox.api.dell.com/support/assetinfo/v4/getassetwarranty/" } else { $Server = "https://api.dell.com/support/assetinfo/v4/getassetwarranty/" } Function Submit-Tags { Param( [String]$Tags , [URI]$URL ) #Write-Verbose $url # Get Data Try { $Warranty = Invoke-RestMethod -URI $URL -Method GET -ContentType 'Application/json' } Catch { $exitcode = 3 Write-Error $Error[0] Break } $Global:Get_DellWarrantyXML = $Warranty foreach ($Asset in $Warranty.AssetWarrantyResponse) { Foreach ($Entitlement in $Asset.assetentitlementData | Where-Object ServiceLevelDescription -NE 'Dell Digitial Delivery') { $row = New-Object PSObject $row | Add-Member -Name "Serial" -MemberType NoteProperty -Value $Asset.assetheaderdata.ServiceTag $row | Add-Member -Name "Model" -MemberType NoteProperty -Value $Asset.productheaderdata.SystemDescription $row | Add-Member -Name "ItemNumber" -MemberType NoteProperty -Value $entitlement.ItemNumber $row | Add-Member -Name "EntitlementType" -MemberType NoteProperty -Value $entitlement.EntitlementType if ($entitlement.ServiceLevelCode.nil)#Look for Nulls in the XML {$row | Add-Member -Name "ServiceLevelCode" -MemberType NoteProperty -Value $NULL} else {$row | Add-Member -Name "ServiceLevelCode" -MemberType NoteProperty -Value $entitlement.ServiceLevelCode} if ($entitlement.ServiceLevelDescription.nil)#Look for Nulls in the XML {$row | Add-Member -Name "ServiceLevelDescription" -MemberType NoteProperty -Value $NULL} else {$row | Add-Member -Name "ServiceLevelDescription" -MemberType NoteProperty -Value $entitlement.ServiceLevelDescription} $row | Add-Member -Name "ServiceLevelGroup" -MemberType NoteProperty -Value $entitlement.ServiceLevelGroup if ($entitlement.ServiceProvider.nil)#Look for Nulls in the XML {$row | Add-Member -Name "ServiceProvider" -MemberType NoteProperty -Value $NULL} else {$row | Add-Member -Name "ServiceProvider" -MemberType NoteProperty -Value ($entitlement.ServiceProvider)} $row | Add-Member -Name "StartDate" -MemberType NoteProperty -Value $entitlement.StartDate $row | Add-Member -Name "EndDate" -MemberType NoteProperty -Value $entitlement.EndDate $row | Add-Member -Name "ExtractDate" -MemberType NoteProperty -Value (Get-Date -format yyyy-MM-ddTHH:mm:ss) $null = $Table.Add($row) #Add the row } } }#Submit-Tags } Process #Process each object in the pipeline; uses a foreach style approach { $Null = $ServiceTags.Add($ServiceTag) #Take pipeline input and create a table to process } End #Final steps. Take the table that was created in the Process block, break it up into $TagLimit chunks, join with a comma, then submit to Dell. Repeat till finished. { Write-Verbose "$($ServiceTags.Count) tags to process." If ($ServiceTags.Count -gt $TagLimit) { Write-Verbose "Service tag list exceeded maximum of $TagLimit and will be broken up into $([math]::Ceiling($ServiceTags.Count / $TagLimit)) groups for submission to Dell." } $Count = 0 $GroupCount = 0 While ($Count -lt $ServiceTags.Count) { $GroupCount ++ If ($ServiceTags.Count -gt $TagLimit) { Write-Verbose "Submitting group $GroupCount of $([math]::Ceiling($ServiceTags.Count / $TagLimit))." } $SubmitTags = $ServiceTags[$Count..($Count + $TagLimit)] -join "," #Write-Verbose "Submitting tags $($ServiceTags.Count - ($ServiceTags.Count - $Count)) through $Count." $URI = $Server + $SubmitTags + "?apikey=" + $Apikey Submit-Tags -Tags $ServiceTags -URL $URI $Count += $TagLimit } Return $Table } }#Function Function Get-DellExpressServiceCode{ <# .NOTES Author: John Tyndall (iTyndall.com) Version: 1.0.0.0 .SYNOPSIS Gets a Dell Express Service Code from a Dell Service Tag. .DESCRIPTION The Get-DellExpressServiceCode cmdlet gets the Dell Express Service Code derived from a Dell Service Tag. A Dell Express Service Code is normally a 10-digit numeric number (i.e., a Base 10 numeral system), which is derived from a Dell Service Tag, which is normally a 5- to 7-digit alphanumeric number (i.e., a Base 36 numeral system). .PARAMETER ServiceTag A Dell Service Tag (e.g., ABC1234). If this parameter is not provided, the Service Tag for the local system is used. .PARAMETER SkipSystemCheck The Get-DellExpressServiceCode is designed to get an Express Service Code from a Service Tag on Dell systems and checks the system manufacturer to ensure that it is a Dell. To bypass this system check, use the SkipSystemCheck switch. .INPUTS System.String. You can pipe one or more strings. .OUTPUTS System.Int64. This cmdlet returns a (long) integer. .EXAMPLE Get-DellExpressServiceCode This commands gets the Express Service Code from the local system's Service Tag. .EXAMPLE Get-DellExpressServiceCode -SkipSystemCheck This command bypasses the system check (to see if the system is manufactured by Dell) and gets the Base 10 representation of the local system's serial number. If multiple Service Tags are passed, this system check is automatically bypassed. .EXAMPLE Get-DellExpressServiceCode ABC1234 This commands gets the Express Service Code from a specified Service Tag (e.g., ABC1234): 22453156048 .EXAMPLE "ABC1234", "XYZ5678" | Get-DellExpressServiceCode This command gets the Express Service Codes from an array of specified Service Tags (e.g., ABC1234, XYZ5678): 22453156048, 73948694948 .LINK "Convert Dell Service Tag to Express Service Code" http://iTyndall.com/scripting/convert-dell-service-tag-to-express-service-code #> param( [Parameter(Mandatory=$False, Position=0, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, HelpMessage="A Dell Service Tag (e.g., ABC1234).")][System.String]$ServiceTag=(Get-WmiObject Win32_Bios).SerialNumber, [switch]$SkipSystemCheck ) Begin{ If($ServiceTag.Count -gt 1) {$SkipSystemCheck = $True} } Process{ If([System.String]::IsNullOrEmpty($ServiceTag)) { Throw [System.Exception] "Could not retrieve system serial number." } If(-not $SkipSystemCheck){ If((Get-WmiObject Win32_ComputerSystem).Manufacturer.ToLower() -notlike "*dell*") { Throw [System.Exception] "Dude, you don't have a Dell: $((Get-WmiObject Win32_ComputerSystem).Manufacturer)" } } $Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" $ca = $ServiceTag.ToUpper().ToCharArray() [System.Array]::Reverse($ca) [System.Int64]$ExpressServiceCode=0 $i=0 foreach($c in $ca){ $ExpressServiceCode += $Alphabet.IndexOf($c) * [System.Int64][System.Math]::Pow(36,$i) $i+=1 } $ExpressServiceCode } End{} } main