Reputation: 91
I have a Csv file with 3 strings for DateTime.
Date;
202202230930;
202202220815;
202202220612;
Because I have to use the Date for naming Snapshots on Proxmox i cant use the - sign. I wanna convert these Dates in to yyyy-MM-dd HH:mm
Now i wanna create a datetime variable in Powershell using that csv file. With the format 'yyyy.MM.dd HH:mm'
I created a foreach so for each date it will ParseExact the string into a datetime.
$datesnapshot = import-csv -Path "D:\autosnap\Datetime.csv" -Delimiter ";"
Foreach($Date in $datesnapshot){
[datetime]::ParseExact($datesnapshot, 'yyyyMMddHH:mm', $null).ToString('yyyy-MM-dd HH:mm')
}
I get the error "String was not recognized as a valid DateTime." I don't know where the problem is because i typed in the Date it is expected to parse and the date i wanna receive. I hope somebody can help.
Kind regards
Upvotes: 0
Views: 2445
Reputation: 59788
A few things to note, the first one:
[datetime]::ParseExact($datesnapshot...
You're iterating over the collection $datesnapshot
but also you're giving ParseExact
the same collection as argument, it should be $date
(the item) instead. In addition, your CSV generates an array of objects (object[]
), where each object has a property with name Date
. If you want to reference the value of your objects you should be using $date.Date
. See about_Properties for more info.
Lastly, the format you're yyyyMMddHH:mm
using will not correctly parse your dates. The format you should use is yyyyMMddHHmm
.
$datesnapshot = @'
Date;
202202230930;
202202220815;
202202220612;
'@ | ConvertFrom-Csv -Delimiter ';'
foreach($Date in $datesnapshot){
[datetime]::ParseExact($Date.Date, 'yyyyMMddHHmm', [cultureinfo]::InvariantCulture).ToString('yyyy-MM-dd HH:mm')
}
Upvotes: 1