You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中DateTime.ParseExact解析EXIF日期抛出FormatException异常

解决PowerShell解析GetDetailsOf返回的EXIF日期时的格式异常问题

问题根源

你遇到的问题核心是:$dir.GetDetailsof($file, 12)返回的日期字符串中包含不可见的Unicode控制字符(比如U+200E左至右标记、U+200F右至左标记)。这些字符肉眼无法直接识别,但会破坏DateTime.ParseExact的严格格式匹配逻辑,导致解析失败——哪怕字符串看起来和硬编码内容完全一致。

从你用Write-Host输出的结果能看到前后的异常符号,就是这些控制字符在作祟。

解决方案

方法1:批量清除所有控制字符

用正则表达式一次性移除所有Unicode控制字符,只保留日期相关的可见字符:

# $index is 12 (for exif 'date taken')
$value = $dir.GetDetailsof($file, $index)
# 移除所有Unicode控制字符和非打印字符
$cleanValue = $value -replace '\p{C}', ''
$cleanValue = $cleanValue.Trim()
if ($cleanValue -and $cleanValue -ne '') {
    return [DateTime]::ParseExact($cleanValue, "g", $null)
}
return $null

\p{C}是正则表达式中匹配所有Unicode控制字符的类别,能覆盖所有不可见的干扰字符。

方法2:针对性移除已知干扰字符

如果已经确认是方向标记类字符,可以直接指定字符编码替换:

$value = $dir.GetDetailsof($file, $index)
# 移除左至右标记(U+200E)和右至左标记(U+200F)
$cleanValue = $value -replace [char]0x200E, '' -replace [char]0x200F, ''
$cleanValue = $cleanValue.Trim()
if ($cleanValue) {
    return [DateTime]::ParseExact($cleanValue, "dd/MM/yyyy HH:mm", $null)
}
return $null

方法3:使用宽松解析逻辑

如果日期格式存在轻微变体可能,可以改用Parse方法替代严格匹配的ParseExact,它会自动兼容更多格式(注意受系统区域设置影响):

$value = $dir.GetDetailsof($file, $index)
$cleanValue = $value -replace '\p{C}', ''
$cleanValue = $cleanValue.Trim()
if ($cleanValue) {
    return [DateTime]::Parse($cleanValue, $null)
}
return $null

验证工具

可以用以下命令查看字符串的实际字符编码,确认是否存在不可见字符:

$value.ToCharArray() | ForEach-Object { [int]$_ }

正常的数字、/、空格、:对应的ASCII码是48-57、47、32、58,如果输出中出现8206、8207这类数值,就是控制字符。

内容的提问来源于stack exchange,提问作者mccrispy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 10:15:36