1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PowerShellで「年 → 月 → 日付ファイル」を自動生成するスクリプト(休日は除外)

Posted at

はじめに

業務や日記用に、年ごとのフォルダ → 月ごとのフォルダ → 平日ごとのファイルを作成したい、という場面がありました。
土日祝日は不要なので、PowerShell のスクリプトで自動化してみます。

ソースコード

以下を make_text.ps1 という名前で保存してください。

param(
    [int]$Year = (Get-Date).Year  # デフォルトは今年
)

# 作業ディレクトリ(必要に応じて変更)
$basePath = "C:\Work"

# 祝日CSV保存パス
$cachePath = "$env:TEMP"
$holidayFile = Join-Path $cachePath 'syukujitsu.csv'
$holidayURL = 'https://www8.cao.go.jp/chosei/shukujitsu/syukujitsu.csv'

# 祝日CSVを3カ月以内に更新、なければ取得
if (!(Test-Path $holidayFile) -or ((Get-Date).AddMonths(-3) -gt (Get-Item $holidayFile).LastWriteTime)) {
    Invoke-WebRequest $holidayURL -OutFile $holidayFile
}

# 祝日リストをハッシュに格納
$holidayList = Get-Content $holidayFile | Select-Object -Skip 1 | ForEach-Object {
    ($_.Split(',')[0] -replace '/','-')
}
$holidays = @{}
foreach ($d in $holidayList) { $holidays[$d] = $true }

# 年フォルダを作成
$yearFolder = Join-Path $basePath $Year
if (!(Test-Path $yearFolder)) {
    New-Item -ItemType Directory -Path $yearFolder | Out-Null
}

# 1月1日から12月31日まで処理
$startDate = [datetime]"$Year-01-01"
$endDate   = [datetime]"$Year-12-31"

for ($d = $startDate; $d -le $endDate; $d = $d.AddDays(1)) {

    # 土日・祝日をスキップ
    if ($d.DayOfWeek -eq 'Saturday' -or $d.DayOfWeek -eq 'Sunday') { continue }
    if ($holidays.ContainsKey($d.ToString("yyyy-MM-dd"))) { continue }

    # 年月フォルダ
    $monthFolder = Join-Path $yearFolder ($d.ToString("yyyyMM"))
    if (!(Test-Path $monthFolder)) {
        New-Item -ItemType Directory -Path $monthFolder | Out-Null
    }

    # 日付ファイル
    $fileName = $d.ToString("yyMMdd") + ".txt"
    $filePath = Join-Path $monthFolder $fileName
    if (!(Test-Path $filePath)) {
        New-Item -ItemType File -Path $filePath | Out-Null
    }
}

実行方法

  1. PowerShell を開く

  2. スクリプトを置いたディレクトリに移動する
    cd C:\Users\xxx\Desktop

  3. 実行する

.\make_text.ps1 -Year 2025

これで C:\Work\2025\202501\250101.txt のようにフォルダとファイルが作成されます。
(土日・祝日のファイルはスキップされます)

実行できないときのエラーと回避法

初めて実行すると、以下のようなエラーが出る場合があります。

このシステムではスクリプトの実行が無効になっているため....

これは 実行ポリシーの制限です。
一時的に回避するには、PowerShell で以下を実行してください。

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

このウィンドウを閉じるまでの間だけ、スクリプトが実行できるようになります。

まとめ

  • PowerShell で日付ごとのファイル生成を自動化
  • 土日祝日は除外可能
  • 実行できないときは Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass で一時回避
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?