0
0

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でテンプレートからテキストファイルを生成する方法

Last updated at Posted at 2025-12-11

概要

私がWindowsを利用する人なので、PowerShellを利用したテキスト出力の話になります。

まえおき

変数を利用して特定フォーマットのテキストを出力したい、ってことあると思うんですが、以前からバッチとかで なんやかんやとやってました。しかし、バッチ処理だと LF改行のテキスト出力ができなかったので、パワーシェルでそれっぽいのを作って今は利用しています。

ファイル配置

Root
├─ DropToRun.bat
├─ variables.ps1 (名前は何でも良い)
└─ template
    └ template1.ps1

ファイルの中身

全部 Shift-JISで書いています。

DropToRun.bat
@echo off
if "%~1"=="" (
    echo 設定変数をドラッグ&ドロップしてください
    echo 何かキーを押すと終了します
    pause
    exit /b
)
powershell -NoProfile -ExecutionPolicy Bypass -File "template\template1.ps1" "%~1"

exit /b
variables.ps1
$PARAM1  = "サンプル"
$PARAM2  = "テスト"
template1.ps1
. $args[0]

$config = @"

- ${PARAM1}:
  - ${PARAM2}

"@

$today = Get-Date -Format "yyMMddHHmm"

$outputDirectory = "${PARAM1}-${PARAM2}-${today}"
if (!(Test-Path ${outputDirectory})) {
    New-Item -ItemType directory -Path ${outputDirectory}
}

$utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False

$filePath = Join-Path ${outputDirectory} "${PARAM2}-CRLF.txt"
[System.IO.File]::WriteAllText(${filePath}, ${config}, $utf8NoBomEncoding)

# 改行コードを変えたい場合
$config2 = ${config} -replace "`r`n", "`n"
$filePath = Join-Path ${outputDirectory} "${PARAM2}-LF.txt"
[System.IO.File]::WriteAllText(${filePath}, ${config2}, $utf8NoBomEncoding)

使い方

variables.ps1を、DropToRun.batに D&Dするだけ。
違うパラメータでデータを吐き出したいときは、variables.ps1を別に用意して中身を書き換えて使ってます。

あとがき

人力で長い設定を作っていると間違えてしまうことはあるので、テンプレートの利用は大事。(うっかりミスを何度かしたことがある)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?