Pocholo
Pocholo

Reputation: 15

How to add date formats on PowerShell Custom Object prop value returns?

However on the console terminal it works just find and that's the output I want when I extract it to csv or txt file and I check type to see if it was string. Sorry maybe I'm just so new to PS that I am not quite familiar with the syntaxes and what's going on under the hood. anyways here is my Here is my hopeful desperate sad attempt Sad Attempt

2nd attempt trying to find what I seek from several websites via google search

Sad attempt 2

This is the specific problem code sorry for the linking(Lazy)

# For testing purposes only i
$SpecifiedSelectObj = $Metadata | Select-Object -Property 'Date taken' | ForEach-Object {
   
    ($_."Date taken").GetType()
    Get-Date $_."Date taken" -Format 'yyyy-MM-dd hh:mm tt' 
<# Associated Error
    | Cannot bind parameter 'Date'. Cannot convert value "‎10/‎12/‎2014 ‏‎5:31 pm" to type 
    "System.DateTime". Error: "String '‎10/‎12/‎2014 ‏‎5:31 pm' was not recognized as
    | a valid DateTime."    
#>

Thank you and much appreciated.

Upvotes: 0

Views: 237

Answers (1)

JosefZ
JosefZ

Reputation: 30103

Solution - remove format characters using Unicode category or Unicode block: \p{}. Use

Get-Date ($_."Date taken" -replace "\p{Cf}", '') -Format 'yyyy-MM-dd hh:mm tt'

Explanation (with an auxiliary script):

Function Get-CodePoint {
    param(
        # named or positional or pipeline: a string to analyse
        [Parameter(Position=0, Mandatory, ValueFromPipeline)]
        $someString
    )
    ([char[]]$someString |
        ForEach-Object { "0x{0:x2}" -f [int]$_ }) -join ','
}

# Analysis
$dateStringCopyPaste = '‎10/‎12/‎2014 ‏‎5:31 pm'
Write-Verbose "Analysis: $(Get-CodePoint -someString $dateStringCopyPaste)" -Verbose
# $dateStringCopyPaste | Format-Hex -Encoding BigEndianUnicode -Verbose

# Solution:- remove format characters using Unicode category: \p{}
$dateRef = [datetime]::Now
$dateString = $dateStringCopyPaste -replace "\p{Cf}", ''
if ( [datetime]::TryParse( $dateString, [ref]$dateRef ) ) {
    Get-Date $dateRef -Format 'yyyy-MM-dd hh:mm tt'
} else {
    Write-Verbose "Solution: $(Get-CodePoint -someString $dateString)" -Verbose
}

Output in the analysis phase:

VERBOSE: Analysis:
0x200e,0x31,0x30,0x2f,0x200e,0x31,0x32,0x2f,0x200e,0x32,0x30,0x31,0x34,0x20,0x200f,0x200e,0x35,0x3a,0x33,0x31,0x20,0x70,0x6d

Those problematic characters 0x200e and 0x200f are

CodePoint  Category Description
---------  -------- -----------
U+200F    Cf-Format Right-To-Left Mark
U+200E    Cf-Format Left-To-Right Mark

Output: .\SO\69156391.ps1

VERBOSE: Analysis:
0x200e,0x31,0x30,0x2f,0x200e,0x31,0x32,0x2f,0x200e,0x32,0x30,0x31,0x34,0x20,0x200f,0x200e,0x35,0x3a,0x33,0x31,0x20,0x70,0x6d
2014-12-10 05:31 PM

Upvotes: 2

Related Questions