neizan neizan - 3 months ago 16
PowerShell Question

Convert data type of property for all objects in an array

Say I have an array of objects:

$a = @(
@{ Name = "A"; Value = "2016-01-02" },
@{ Name = "B"; Value = "2016-01-03" },
@{ Name = "C"; Value = "2016-01-04" }
)


The
Value
property is currently a
String
. I want to convert the
Value
property of each object to a
DateTime
. I could accomplish this with a
for
loop, but I was wondering if there is a more direct way to do it.

Answer

Yes, calculated properties.

$a | select @{N='Name';E={$_.Name}}, @{N='Value';E={ [datetime]$_.Value }}