0

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

2
  • 2
    Please post your code as plain text, not screenshots (neither of which appear to be of your code btw) Commented Feb 23, 2022 at 12:54
  • 2
    You're giving ParseExact the collection $datesnapshot and not the item $Date as argument. Among other things Commented Feb 23, 2022 at 13:00

1 Answer 1

1

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')
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, iam new to powershell and have to learn a lot of things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.