投稿

1月, 2017の投稿を表示しています

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

Google Blogger "Blog This" URL パラメーター

Quick Edit Pencil
https://www.blogger.com/blog-this.g?

u=ハイパーリンクURL?spref%3Dbl

&

n=ブログタイトルとハイパーリンクタイトル

&

Powershell Get-Date 英語の月名を表示

Quick Edit Pencil
$us = New-Object system.globalization.cultureinfo("en-US")
(Get-Date).ToString("yyyy MMM d",$us)
2017 Jan 14

MMM 月の省略名。
MMMM 月の完全名。

MSDN カスタム日時書式指定文字列