日報の日付を書き換えるのがいちいち面倒だったので。
- 日付を取得
- テンプレートファイルのYYYY/MM/DDを書き換える
ことを目指す。
内容的には以下の記事の続きです。
powershellスクリプトでテキストファイルを文字列置換
powershellで日付を取得する方法
Get-Date
コマンドを用いる。単にこのGet-Date
コマンドを打つと、以下のように表示される。
console
PS > Get-Date
2021年5月21日 1:38:54
オプションをつけることで、細かく情報を抜き出すことができる。
オプションのつけ方にも色々ある。
詳細は以下の記事を参照。
https://cheshire-wara.com/powershell/ps-cmdlets/system-service/get-date/
console
PS > (Get-Date).Year
2021
PS > Get-Date -UFormat %Y
2021
PS > Get-Date -Format yyyy
2021
PS > (Get-Date).Month
5
PS > Get-Date -UFormat %m
05
PS > Get-Date -Format MM
05
今回は月, 日も2桁で欲しいので、Get-Date -UFormat %m
の形式を使う。
ファイルに書き出す
本題。手順としては、
- テキストファイルから文字列を読み込んで、
- powershellで日付を取得し、
- 文字列中の
YYYY, MM, DD
を日付に置き換え、 - 新しいテキストファイルに出力する
の4ステップを行う。
コードと実行結果は以下。
template.txt
今日はYYYY年MM月DD日です
create_report_without_args.ps1
$yyyy = Get-Date -UFormat %Y #年(西暦四桁)。ちなみに%yだと西暦下二桁。
$mm = Get-Date -UFormat %m #月(01~12)
$dd = Get-Date -UFormat %d #日(01~31)
Get-Content -Encoding UTF8 ./template.txt `
| ForEach-Object {$_ -replace "YYYY", $yyyy} `
| ForEach-Object {$_ -replace "MM", $mm} `
| ForEach-Object {$_ -replace "DD", $dd} `
| Out-File -Encoding UTF8 $yyyy$mm$dd.txt -NoClobber
20210521.txt
今日は2021年05月21日です
今日の日付を反映できたことがわかる。
まとめ
シェルスクリプト、便利だが覚える機会がない…