概要
テスト環境や本番環境のアプリリリースにて一部(IPアドレス等)以外、リリース手順が同じ場合
また、メール送信ファイル作成にてユーザ情報以外同一の場合など
毎回、記述するのが面倒なのでシンプルなテンプレートエンジンを作成する
テンプレートファイルと入力データよりファイルを出力する
・テンプレートファイルが存在しない場合はメッセージを出力してなにもしない
・テンプレートの変換は「Hashtable」を使う( @{キー名 = 値; キー名 = 値; ....... })
「Hashtable」の「キー名」にテンプレートに記述した値を設定、「値」に変更する入力データを設定
文字コードのデフォルトは「UTF8」(テンプレートファイル、出力ファイル)
関数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ------------------------------------------------------------------ | |
# テンプレートファイルと入力データよりファイルを出力する | |
# 関数名:Render-Template | |
# 引数 :TemplateFilePath テンプレートファイルパス | |
# :DataObject データ | |
# :OutPutFilePath 出力ファイルパス | |
# :Encoding 文字コード | |
# 戻り値:なし | |
# ------------------------------------------------------------------ | |
function Render-Template([String]$TemplateFilePath, [System.Collections.Hashtable]$Data, | |
[String]$OutPutFilePath, [String]$Encoding = "UTF8"){ | |
# テンプレートファイルの存在チェック | |
if(-not(Test-Path -LiteralPath $TemplateFilePath -PathType Leaf)){ | |
Write-Host "指定したテンプレートファイルが存在しません" | |
break | |
} | |
# テンプレートファイル読み込み | |
$template = Get-Content $TemplateFilePath -Encoding $Encoding | |
# 置換 | |
foreach ($value in $Data.keys){ | |
$template = $template -replace $value , $Data[$value] | |
} | |
# ファイル出力 | |
$template | Out-File $OutPutFilePath -Encoding $Encoding | |
} |
実行例
・テンプレートファイル(Mail_Template.txt)
{LAST_NAME} {FIRST_NAME} 様 ご購入ありがとうございます。 ~省略~・powershell実行
# メールテンプレート指定 $MailTemplateFile = "C:\template\Mail_Template.txt" # ユーザ情報セット $User = @{"{LAST_NAME}"="山田"; "{FIRST_NAME}"="太郎"} # 出力ファイル指定 $MailFile = "C:\Temp\Mail_001.txt" # 実行 Render-Template -TemplateFilePath $MailTemplateFile -Data $User -OutPutFilePath $MailFile