Neil P
Neil P

Reputation: 3190

How to declare an array using get-date?

I'd like to declare an array of dates in powershell, it's not a continuous range, so I cant do anything clever with loops.

I've tried using the array notation with a call to get-date, as below, but this returns an error

$logDateList = 
@(Get-Date -Year 2017 -Month 08 -Day 22 -Hour 13
,Get-Date -Year 2017 -Month 08 -Day 20 -Hour 22)

How can I declare an array of dates in powershell?

Upvotes: 2

Views: 2270

Answers (3)

TessellatingHeckler
TessellatingHeckler

Reputation: 28983

You can cast a string to a datetime like this:

[datetime]'2017-08-22 13:00'

and make your array

$logDateList = [datetime]'2017-08-22 13:00', [datetime]'2017-08-20 22:00'

and if you're doing that, make it one array of string dates, and cast to an array of datetime

[datetime[]] $logDateList = @(
    '2017-08-22 13:00', 
    '2017-08-20 22:00'
)

I put them in ISO standard yyyy-MM-dd hh:mm order to avoid US/UK parsing confusion.

Upvotes: 2

Mark Wragg
Mark Wragg

Reputation: 23355

I'd argue that you should still use a loop for this to save yourself some code duplication:

$logDateList = '20 Aug 2017 22:00','22 Aug 2017 22:13' | ForEach-Object { Get-Date $_ }

Example using text for months in the interests of avoiding regional issues but you could format your dates in whatever way you like that works for you.

Upvotes: 3

henrycarteruk
henrycarteruk

Reputation: 13227

Just wrap each Get-Date in brackets:

$logDateList = @((Get-Date -Year 2017 -Month 08 -Day 22 -Hour 13),(Get-Date -Year 2017 -Month 08 -Day 20 -Hour 22))

Upvotes: 3

Related Questions