Jaxer
Jaxer

Reputation: 37

Convert string expression to date type in PowerShell

I have below code in PS:

Connect-AzureAD 
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent 
Get-AzureADUser -All:$true |Select ObjectId,UserPrincipalName,@{Name='ExpirationDate'; Expression={(Get-AzureADUserExtension -ObjectId $_.ObjectId).Get_Item("createdDateTime")}} 
| Export-CSV "$PSScriptRoot\userslist.csv"
Disconnect-AzureAD

I want to convert string createdDateTime to a dateTime format, so I can add +60 days to it (.AddDays(60)). I tried without conversion but it didn't work.

Expression={(...).Get_Item("createdDateTime")}}

I tried also with function [datetime]::ParseExact but I did something wrong (no error in the console), because the column in output was blank.

Please advise

EDIT This is what I get after I run the whole script Pamela gave. No error in the console. Any ideas why is so?

enter image description here

Upvotes: 1

Views: 694

Answers (1)

unknown
unknown

Reputation: 7483

Tried with your code and get the time, it looks like "2/16/2021 5:55:03 AM":

enter image description here

So I format the string with 'M/d/yyyy H:mm:ss tt'.

$string = "2/16/2021 5:55:03 AM"
[Datetime]::ParseExact($string, 'M/d/yyyy H:mm:ss tt', $null)

enter image description here

As you said in the comment, your CreationDate is like "19.10.2020 13:55:29", so d.M.yyyy H:mm:ss should work(not sure M or MM in yours, you could check more CreationDate).

Format the datetime and add 60 days:

Get-AzureADUser -All:$true |Select ObjectId,UserPrincipalName,@{Name='ExpirationDate'; Expression={[Datetime]::ParseExact((Get-AzureADUserExtension -ObjectId $_.ObjectId).Get_Item("createdDateTime"), 'd.M.yyyy H:mm:ss', $null).AddDays(60)}}

enter image description here

Upvotes: 1

Related Questions