LoginSignup
0
0

More than 1 year has passed since last update.

powershellスクリプトで日付取得してテキストファイルの日付を書き換え

Last updated at Posted at 2021-05-20

日報の日付を書き換えるのがいちいち面倒だったので。

  • 日付を取得
  • テンプレートファイルの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の形式を使う。

ファイルに書き出す

本題。手順としては、

  1. テキストファイルから文字列を読み込んで、
  2. powershellで日付を取得し、
  3. 文字列中のYYYY, MM, DDを日付に置き換え、
  4. 新しいテキストファイルに出力する

の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日です

今日の日付を反映できたことがわかる。

まとめ

シェルスクリプト、便利だが覚える機会がない…

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0