Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
davehope opened this issue May 30, 2024 · 0 comments
Closed

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

davehope opened this issue May 30, 2024 · 0 comments

Comments

@davehope
Copy link
Contributor

davehope commented May 30, 2024

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'
                        }
@davehope davehope changed the title Use [DateTime]::TryParseExact() instead of [DateTime]::ParseExact() Prevent exception thrown by [DateTime]::ParseExact() May 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants