Converting DateTime Obtained from Microsoft Graph Call to PowerShell Date and Time Format

Table of Contents

Convert a Text String to a Correct Date Time Format

We have a PowerShell script where we perform the call to get the renewal date of a Microsoft 365 subscription with Microsoft Graph API.

$subId = '27689fc1-239d-491f-b11d-06f0d3ab7819'
$uri = "https://graph.microsoft.com/beta/directory/subscriptions/$subId"
$RenewalDate = (Invoke-RestMethod -Method GET -Headers $headers -Uri $uri).nextLifecycleDateTime
$RenewalDate
PS C:\> $RenewalDate
2024-08-13T00:00:00Z

The output format like the following “2024-08-13T00:00:00Z”. This is not recognized as a valid DateTime format when we’re trying to use it with a PowerShell operator.

PS C:> ($RenewalDate – $((Get-Date).Date)).Days
Cannot convert value “2024-08-13T00:00:00Z” to type “System.Int32”. Error: “Input string was not in a correct format.”
At line:1 char:19
+ ($RenewalDate – $((Get-Date).Date)).Days
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToInteger

For example, we got the following error when counting the days to renew from today.

Converting DateTime Obtained from Microsoft Graph Call to PowerShell Date and Time Format

When we check it with Get-Member we can see its type is string.

PS C:\> $RenewalDate
2024-08-13T00:00:00Z
PS C:\> $RenewalDate | Get-Member

   TypeName: System.String

The type of a date time object in PowerShell should be System.DateTime.

PS C:\> $((Get-Date).Date) | Get-Member

   TypeName: System.DateTime

To dealing with this, we need to convert the System.String to System.DateTime.

[Datetime]::ParseExact($RenewalDate, 'yyyy-MM-ddTHH:mm:ssZ', $null)

As you can see, now the renewal date shows as normally.

Converting DateTime Obtained from Microsoft Graph Call to PowerShell Date and Time Format

Then we can use it as a PowerShell object with PowerShell operators.

Converting DateTime Obtained from Microsoft Graph Call to PowerShell Date and Time Format

Leave a Comment

Required fields are marked *