powershell - 无法从JPG文件的DateTaken属性将字符串转换为整数变量

标签 powershell

我有一个脚本正在使用JPG文件中的EXIF数据来查找DateTaken值。找到后,将数据放在$Year$Month变量中。

$objShell  = New-Object -ComObject Shell.Application
$folders = (Get-ChildItem G:\ServerFolders\Photos\UnSorted\ -Directory -Recurse -force).FullName

foreach ($Folder in $folders) {
    $objfolder = $objShell.Namespace($folder)

    foreach ($file in $objFolder.Items()) {
        if ($objfolder.GetDetailsOf($file, 156) -eq ".jpg") {
            $yeartaken = ($objFolder.GetDetailsOf($File, 12)).Split("/")[2].Split(" ")[0]
            $month = $objFolder.GetDetailsOf($File, 12).Split("/")[1]
            $monthname = (Get-Culture).DateTimeFormat.GetMonthName($month)

            Write-Host $file.Name
        }
    }
}

因此,如果文件的DateTaken为06/10/2016,则$yeartaken2016,而$month10
然后,我将Get-Culture转换为10月份。这不起作用,因为它将$month视为字符串。

无法将“GetMonthName”的参数“month”(值:“10”)转换为
类型“System.Int32”:“无法将值“10”转换为类型“System.Int32”。
错误:“输入字符串的格式不正确。”
行:1字符:3
+(获取文化).DateTimeFormat.GetMonthName($ month)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo:未指定:(:) [],MethodException
+ FullyQualifiedErrorId:MethodArgumentConversionInvalidCastArgument

我尝试使用强制转换或转换将其转换为Integer值,但由于某种原因,它将无法转换。

PS> [int] $ Test = $ month

无法将值“10”转换为“System.Int32”。错误:“输入字符串原为
格式不正确。”
在第1行:char:1
+ [int] $ Test = $ month
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo:MetadataError:(:) [],ArgumentTransformationMetadataException
+ FullyQualifiedErrorId:RuntimeException

最佳答案

处理日期的一种更好的方法是将日期字符串转换为实际的DateTime对象,该对象提供您要查找的所有信息:

$culture = [Globalization.CultureInfo]::InvariantCulture
$pattern = 'dd\/MM\/yyyy'

$datestring = $objFolder.GetDetailsOf($File, 12).Split(' ')[0]
$datetaken  = [DateTime]::ParseExact($datestring, $pattern, $culture)

$year      = $datetaken.Year
$month     = $datetaken.Month              # month (numeric)
$monthname = $datetaken.ToString('MMMM')   # month name

假设日期后面跟随着一个格式为HH:mm:ss的时间,那么您可以扩展代码来处理时间:
$culture = [Globalization.CultureInfo]::InvariantCulture
$pattern = 'dd\/MM\/yyyy HH:mm:ss'

$datestring = $objFolder.GetDetailsOf($File, 12)
$timestamp  = [DateTime]::ParseExact($datestring, $pattern, $culture)

$year      = $timestamp.Year
$month     = $timestamp.Month              # month (numeric)
$monthname = $timestamp.ToString('MMMM')   # month name
$hour      = $timestamp.Hour
...

关于powershell - 无法从JPG文件的DateTaken属性将字符串转换为整数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57382251/

相关文章:

powershell - ExpandProperty - 管道中缺少的对象

azure - 从 Azure 中的虚拟网络网关获取虚拟网络详细信息

powershell - 在本地运行时,Invoke-Command是否在当前作用域或子作用域中运行?

powershell - 如何确定 EventLog 是否已存在

sql - Powershell foreach SQL Server查询随机整理DataSet

python - 为什么 'python' 在 powershell 中无法识别?

powershell - 从 C# 调试 powershell 脚本文件 (PS1)

powershell - 使用 Invoke-Command 在提升的 session 中运行 Start-Process

powershell - IF 语句中的动态条件参数?

windows - 自动生成对 powershell 命令的响应?