servicenow-powershell
servicenow-powershell copied to clipboard
Prevent exception thrown by [DateTime]::ParseExact()
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'
}