Snow-Shell / servicenow-powershell

PowerShell module to automate ServiceNow service and asset management. This module can be used standalone, with Azure Automation, or Docker.
Apache License 2.0
359 stars 170 forks source link

Prevent exception thrown by [DateTime]::ParseExact() #265

Closed davehope closed 2 months ago

davehope commented 3 months ago

ServiceNow module 4.0.3 uses [DateTime]::ParseExact() in Invoke-ServiceNowRestMethod line 253 + 259. This can result in an exception being thrown, and PowerShell's $error getting populated which it'd be nice to avoid.

An example of where this occurs: DateTimeFormat: dd/MM/yyyy HH:mm:ss SNResult.Property: '2024-05-30 10:40:38'

One approach might be to pass a string[] to ParseExact to make the conversion more likely to succeed. Something like:

                        Try {
                            # Extract the default Date/Time formatting from the local computer's "Culture" settings, and then create the format to use when parsing the date/time from Service-Now
                            $CultureDateTimeFormat = (Get-Culture).DateTimeFormat
                            $DateFormat = $CultureDateTimeFormat.ShortDatePattern
                            $TimeFormat = $CultureDateTimeFormat.LongTimePattern
                            $DateTimeFormat = [string[]]@("$DateFormat $TimeFormat", 'yyyy-MM-dd HH:mm:ss')
                            $SNResult.$Property = [DateTime]::ParseExact($($SNResult.$Property), $DateTimeFormat, [System.Globalization.DateTimeFormatInfo]::InvariantInfo, [System.Globalization.DateTimeStyles]::None)
                        }
                        Catch {
                            # If the local culture and universal formats both fail keep the property as a string (Do nothing)
                            $null = 'Silencing a PSSA alert with this line'
                        }