Shell.Application getDetailsOf jpg Exif DateTaken无效DateTime

时间:2018-05-05 08:32:36

标签: string powershell datetime metadata

我正在使用powershell从Jpg照片中获取EXIF数据,我希望获取Date Taken字段,然后将其翻转为读取yyyy-MM-dd,这将成为文件夹的名称。下面列出了脚本源,用于完整的脚本检查。

下面的脚本功能,但我得到日期格式为MM-dd-yyyy的文件夹,我觉得我错过了一些非常简单的东西。非常感谢任何帮助!

这个问题File date metadata not displaying properly正是我观察到的行为,返回的日期时间字符串是22个字符,我试图用[char]8206 and [char]8207替换''但是返回错误:

  

使用“3”参数调用“ParseExact”的异常:“字符串不是
  被确认为有效的DateTime。“
  $ NewDateFormat = [datetime] :: ParseExact($ DateTaken2,'yyyy-MM-dd',$ null)

#script source:
http://superwidgets.wordpress.com/category/powershell/
http://superwidgets.wordpress.com/2014/08/15/powershell-script-to-get-detailed-image-file-information-such-as-datetaken/

萨姆布特罗斯的剧本 v1.0 - 2015年1月11日

$Images | ForEach-Object { $DateTaken = $_.DateTaken.Split(' ')[0].Replace('/','-')


    $DateTaken2 = ($DateTaken -replace [char]8206) -Replace([char]8207)

    $NewDateFormat = [datetime]::ParseExact($DateTaken2, 'yyyy-MM-dd',$null)

    IF (-not (Test-Path $Source\$DateTaken2)){"Create $Source\$DateTaken2"

    New-Item -Path "$Source\$DateTaken2" -ItemType Directory -Confirm:$false}

    Move-Item -Path $_.FullName -Destination "$Source\$DateTaken2" -Confirm:$false

    }

1 个答案:

答案 0 :(得分:1)

我会说你的逻辑中的问题是你给ParseExact格式 您想要的,而不是元数据中的格式。此方法旨在从字符串创建DateTime对象(基于您提供的格式),而不是格式化DateTime对象。

你可以试试这个(在500张图片的文件夹上测试 - 删除-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脚本:)。