Import from CSV and cast properties to correct type
suggest changeBy default, Import-CSV imports all values as strings, so to get DateTime- and integer-objects, we need to cast or parse them.
Using Foreach-Object:
> $listOfRows = Import-Csv .\example.csv
> $listOfRows | ForEach-Object {
#Cast properties
$_.DateTime = [datetime]$_.DateTime
$_.Integer = [int]$_.Integer
#Output object
$_
}
Using calculated properties:
> $listOfRows = Import-Csv .\example.csv
> $listOfRows | Select-Object String,
@{name="DateTime";expression={ [datetime]$_.DateTime }},
@{name="Integer";expression={ [int]$_.Integer }}
String DateTime Integer
------ -------- -------
First 01.12.2016 12:00:00 30
Second 01.12.2015 12:00:00 20
Third 01.12.2015 12:00:00 20
That date text is one culture's formatting of 2016-12-01T12:00:00, 2015-12-01T12:00:00, and 2015-12-01T12:00:00. Your culture may print the same values differently. Select-Object here returns new objects; it does not change $listOfRows.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents