read value from file; then convert value to date

by cyscript at 2013-03-08 07:38:40

I have tried several ways to convert a value(read from a txt-file) to a date. Still no success.
It only works, if I assign a string value directly to a variable
At the prompt, this works:
$inp_date = “20/02/2013”

But, if I parse the read value from a file, then it doesn’t works:
Content of textfile.txt has these lines:
xxxx 20/02/2013 16:01:02
xxxx 21/02/2013 13:03:03

Content of script to extract the date:
$inp = “.\textfile.txt”
$date_lines = Select-String $inp -pattern “/201” | Select-Object Line
$date_lines[0] # for the test, just use the first line= xxxx 20/02/2013 16:01:02
$ar = $date_lines[0] -Split " "
$ar[1] # 20/02/2013 <-- this is the extracted date
[datetime]]) <-- this doesn’t retun anything back

No result is given back. Hope someone knows what is wrong.
by kittH at 2013-03-08 08:06:53
This works for me:

$inp_date = “20/02/2013”
by cyscript at 2013-03-08 11:53:14
It is very strange. I have already tried your code. This doesn’t work for me:
$inp_date = “20/02/2013”

Exception calling “ParseExact” with “3” argument(s): "String was not recognized as a valid DateTime.“

But, this works for me:
$inp_date = “20/02/2013”

However, this is not what I want. I need to read a line from my “text.txt” file; get the part with the date out of the line and put the value in a variable. At the end use the PARSE command.
In my example script, $ar[1] contains the date (after extracting the value from a line).
But, then [datetime]]) doesn’t return anything back.
by ArtB0514 at 2013-03-08 12:02:19
Would using native PowerShell cmdlets work in place of dropping down into .NET? Get-Date returns a [DateTime] object.

Get-Date -Date $ar[1]
by cyscript at 2013-03-08 13:04:03
Unfortunately, Get-Date -Date $ar[1] doesn’t return anything back on screen (just like my code).
by ArtB0514 at 2013-03-08 13:56:04
You might have a culture issue. Run
If it says “en-US”, then that’s the nature of your problem. en-US wants “02/20/2013” instead of “20/02/2013”. There’s a script at that will let you specify the correct culture for a single command.
by Malkey at 2013-03-08 16:46:06
These examples appear to work.

Your example Post #1.
$inp = “.\textfile.txt”
$date_lines = Select-String $inp -pattern “/201” | Select-Object Line
$date_lines[0] # for the test, just use the first line= xxxx 20/02/2013 16:01:02
$ar = $date_lines[0] -Split " “
Get-Date $ar[1] -f “yyy-MM-dd” # <-- Returns 2013-02-20

And using a Regular Expression approach capturing date and time.
$inp = Get-Content .\textfile.txt | Out-String
$reg = [regex]”\d{1,2}.\d{1,2}.\d{4}\s\d{1,2}:\d{1,2}:\d{1,2}”
$Date = $reg.Matches($inp) | % { $_.value }
Get-Date $Date[0] -f "yyyy/MM/dd HH]

Edit: If these examples do not work, as ArtB0514 implied, you might need “Set-Culture” with an appropriate culture name, or not.
by cyscript at 2013-03-09 01:01:41
Thanks Malkey: It works!
And, thanks to others who tried to help.