PowerShell: 詳細情報から取得した日付のフォーマット

Quick Edit Pencil
ファイルのプロパティ詳細情報の撮影日時(ID:12)と取得日時(ID:129)を取って日付フォーマットを変えるときに=DateTimeオブジェクトにする時にエラーが出る。

Get-Dateでも[System.DateTime]::Now(短縮[DateTime])でもエラーが出る。

Get-Date : パラメーター 'Date' をバインドできません。値 "‎2017/‎01/‎07 ‏‎9:11" を型 "System.DateTime" に変換できません。エラー: "文字列は有効な DateTime ではありませんでした。"
発生場所 C\:詳細情報から取得した日付のフォーマット.ps1:41 文字:10
+ Get-Date $date_org
+          ~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Date]、ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand
 
値 "‎2017/‎01/‎07 ‏‎9:11" を型 "System.DateTime" に変換できません。エラー: "文字列は有効な DateTime ではありませんでした。"
発生場所 C\:詳細情報から取得した日付のフォーマット.ps1:43 文字:1
+ [DateTime]$date_org
+ ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) []、RuntimeException
    + FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider

原因は撮影日時(ID:12)と取得日時(ID:129)の日付には何かの制御文字が入っているのでDateTimeオブジェクト規則から外れるようです。



とりあえず正規表現を使いこの制御文字を外します。

$pat = "(\d{4}).*?(\d{1,2}).*?(\d{1,2}).*?(\d{1,2}.*?$)"
$regex = [regex]$pat
$hash_table = $regex.Matches($date_org)
$hash_table
$array = $hash_table.Groups

$date_new =  [string]$array[1] + "-" + [string]$array[2] + "-" + [string]$array[3] + " " + [string]$array[4]

$date = Get-Date $date_new -Format "F"

サンプルスクリプト

# 詳細情報から取得した日付のフォーマット

# ファイルのフルパス

$path = "C:\test.jpg"

# フルパスを分割
$folder = Split-Path $path
$file = Split-Path $path -Leaf
#Write-Host ディレクトリーパス: $folder"`r`n"ファイル名: $file

# WSHオブジェクトを作成
$shell = New-Object -ComObject Shell.Application

# フォルダの指定
$shellFolder = $shell.NameSpace($folder)

# ファイルの指定
$shellFile = $shellFolder.parseName($file)

# 詳細プロパティの要約 -1を指定
#Write-Host $shellFolder.GetDetailsOf($shellFile,-1)

# 詳細プロパティを列挙 とりあえず310項目
#for ($i=0; $i -lt 310; $i++){
#    Write-Host $i `t $shellFolder.GetDetailsOf($shellFolder.Items(),$i) `t $shellFolder.GetDetailsOf($shellFile,$i)
#}

# 詳細プロパティを取得
$datailId = 12 #撮影日
Write-Host $datailId `t $shellFolder.GetDetailsOf($shellFolder.Items(),$datailId) `t $shellFolder.GetDetailsOf($shellFile,$datailId)

$date_org = $shellFolder.GetDetailsOf($shellFile,$datailId)

# Get-DateでDateTimeオブジェクトにする(エラーが出る)
Get-Date $date_org
[DateTime]$date_org

$pat = "(\d{4}).*?(\d{1,2}).*?(\d{1,2}).*?(\d{1,2}.*?$)"
$regex = [regex]$pat
$hash_table = $regex.Matches($date_org)
$hash_table
$array = $hash_table.Groups

$date_new =  [string]$array[1] + "-" + [string]$array[2] + "-" + [string]$array[3] + " " + [string]$array[4]

$date = Get-Date $date_new -Format "F"

Write-Host $date

このブログの人気の投稿

書字方向 横書方向変換スクリプト 左書きから右書きへ(コピペ用途)

PowerShellのGetDetailsOf メソッドでプロパティの詳細情報のID番号と項目名を列挙します

PowerShellで複数ファイルのプロパティを取得する方法(準備編)

簡単 YouTube動画をダウンロード、音声のみ保存する方法 2019

DOMノードオブジェクトを文字列に変換する

ヤバい!JAPANNEXT WQHD対応 27型ワイド液晶ディスプレイ「JN-IPS2716WQHD」を注文してみた!!!

決定版 Edgeでローカルファイルを開く パワーシェルスクリプト (ウインドウズでドロップレット)

PowerShellでJPG画像のリサイズとウォーターマーク画像との合成を同時に行う