我会说你的逻辑中的问题是你给的 ParseExact 格式 您想要的,而不是元数据中的格式。这种方法旨在创建一个 DateTime 来自字符串的对象(基于您提供的格式),而不是格式化 DateTime 宾语。
ParseExact
DateTime
你可以试试这个(在500个图片的文件夹上测试 - 删除 -WhatIf 行动):
-WhatIf
$folderPath = "C:\UnsortedPics" $newRootFolderPath = "C:\SortedPics" # create root folder if does not exist New-Item $newRootFolderPath -ItemType Directory -Force -WhatIf | Out-Null # create shell object $shell = New-Object -ComObject Shell.Application # create folder object $folder = $shell.NameSpace($folderPath) foreach ($file in $folder.Items()) { # get raw date from file metadata $rawDate = ($folder.GetDetailsOf($file, 12) -replace [char]8206) -replace [char]8207 if ($rawDate) { try { # parse to date object $date = [DateTime]::ParseExact($rawDate, "g", $null) # you could also use this without try/catch: #$date = New-Object Datetime #$parseSuccess = [DateTime]::TryParseExact($rawDate, "g", (Get-Culture), [System.Globalization.DateTimeStyles]::None, [ref]$date) # get wanted format $dateString = Get-Date $date -Format "yyyy-MM-dd" # create path $newFolderPath = Join-Path $newRootFolderPath $dateString # create folder if does not exist New-Item $newFolderPath -ItemType Directory -Force -WhatIf | Out-Null # move file Move-Item $file.Path -Destination $newFolderPath -Confirm:$false -WhatIf } catch { # ParseExact failed (would also catch New-Item errors) } } else { # no value for "Date Taken" property } }
使用这种方法,您不再需要TechNet脚本:)。