Powershell 向导们下午好!
我希望有人可以向我解释如何解决这个问题,更重要的是问题到底是什么!
我正在尝试修复几年前编写的一个旧脚本,该脚本会搜索文件属性上的多个日期并选择一个用于重命名该文件。
我遇到的问题是,当我使用 parseExact 时,它无法读取从文件中读取的日期字符串...但如果我手动在 powershell 中键入相同的字符串,它就可以工作!
请注意,此脚本仅在我的电脑上运行,并且只需要处理我的文件格式中的日期,因此我不太担心 $null 的使用,除非它相关。
参见下面的示例:
Write-Host "TEST 1"
$DateTime = [DateTime]::ParseExact("240720211515","ddMMyyyyHHmm",$null)
Write-Host $DateTime # WORKS!
Write-Host "TEST 2"
$DateTime2 = [DateTime]::ParseExact("240720211515","ddMMyyyyHHmm",$null)
Write-Host $DateTime2 # FAILS!
看起来一样吧?
这是一个更真实的例子,说明我所做的事情失败了
$file = Get-Item "C:\SomeFolder\somefile.jpg"
$shellObject = New-Object -ComObject Shell.Application
$directoryObject = $shellObject.NameSpace( $file.Directory.FullName )
$fileObject = $directoryObject.ParseName( $file.Name )
$property = 'Date taken'
for(
$index = 5;
$directoryObject.GetDetailsOf( $directoryObject.Items, $index ) -ne $property;
++$index) { }
$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)
Write-Host $photoDate # <-- This reads 03/08/2021 09:15
$output = [DateTime]::ParseExact($photoDate,"dd/MM/yyyy HH:mm",$null) # <-- This fails
Write-Host $output
# If i manually type in here it works.... If I copy and paste from the Write-Host it fails...
$someInput = "03/08/2021 09:15"
$workingOutput = [DateTime]::ParseExact($someInput,"dd/MM/yyyy HH:mm",$null)
Write-Host $workingOutput
最佳答案
对于遇到此问题的其他人来说,似乎添加了隐形字符。感谢@SantiagoSquarzon 提供的位置
这针对我的特定目的修复了它:
$photoDate = $directoryObject.GetDetailsOf($fileObject, $index)
$utfFree = $photoDate -replace "\u200e|\u200f", ""
关于windows - 使用 Powershell [DateTime]::ParseExact - 有趣的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74617304/