1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PowerShellのスクリプトテンプレート

Last updated at Posted at 2022-11-13

PowerShellのスクリプトをいっぱい書くことになったので、
ログ出力とかのテンプレートを固めておきたいと思って投稿しました。

フォルダ構成はこんな感じ ※logフォルダは自動で作成されるので手で作る必要はないです。
相対パスで動くようにしているので、基本どこに置いても動作すると思います。
※バッチファイルについてはこちら
image.png

実行すると↓みたいなlogが作成される。
image.png

中身はこんな感じ。
image.png

ソースコード

#==============日時・ログファイル定義==============
$Date = Get-Date -Format yyyy_MM_dd
$Time = Get-Date -Format HH_mm_ss
$Now = "$Date`_$Time"
$Name_ps1 = [System.IO.Path]::GetFileNameWithoutExtension($PSCommandPath)
$Log_Ps1 = "$PSScriptRoot\log\$Name_ps1`_$Now`_$env:COMPUTERNAME`_$env:USERNAME`.log"

#==============スクリプト終了定義==============
Function Finish_Ps1{
    Write-Host (Get-Date -Format HH_mm_ss) "`t**********スクリプトを終了します**********"
    Stop-Transcript
    Exit
}

#==============スクリプト開始==============
Start-Transcript $Log_Ps1
Write-Host (Get-Date -Format HH_mm_ss) "`t**********スクリプトを開始します**********"
Write-Host ""

#==============処理Aを記述==============
Write-Host (Get-Date -Format HH_mm_ss) "`t▼▼▼▼▼▼▼▼▼▼処理Aを開始します▼▼▼▼▼▼▼▼▼▼"
Write-Host (Get-Date -Format HH_mm_ss) "`t==========A-1実行中=========="
Write-Host (Get-Date -Format HH_mm_ss) "`t==========A-2実行中=========="
Write-Host (Get-Date -Format HH_mm_ss) "`t==========A-3実行中=========="
Write-Host (Get-Date -Format HH_mm_ss) "`t▲▲▲▲▲▲▲▲▲▲処理Aを終了します▲▲▲▲▲▲▲▲▲▲"
Write-Host ""

#==============処理Bを記述==============
Write-Host (Get-Date -Format HH_mm_ss) "`t▼▼▼▼▼▼▼▼▼▼処理Bを開始します▼▼▼▼▼▼▼▼▼▼"
Write-Host (Get-Date -Format HH_mm_ss) "`t==========B-1実行中=========="
Write-Host (Get-Date -Format HH_mm_ss) "`t==========B-2実行中=========="
Write-Host (Get-Date -Format HH_mm_ss) "`t==========B-3実行中=========="
Write-Host (Get-Date -Format HH_mm_ss) "`t▲▲▲▲▲▲▲▲▲▲処理Bを終了します▲▲▲▲▲▲▲▲▲▲`n"
Write-Host ""

#==============スクリプト終了==============
Finish_Ps1

1
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?