Skip to content

Instantly share code, notes, and snippets.

@gok11
Created November 26, 2024 06:10
Show Gist options
  • Select an option

  • Save gok11/80f24b8a31b2bb2ca307c543b485e745 to your computer and use it in GitHub Desktop.

Select an option

Save gok11/80f24b8a31b2bb2ca307c543b485e745 to your computer and use it in GitHub Desktop.
指定したフォルダにあるテキストファイルを今日の日付のメモとして複製するPowerShellスクリプト
Set-Location $PSScriptRoot
$noteFolder = ""
$noteNamePrefix = "note_"
function Test-Setting {
# フォルダ指定チェック
if ($null -eq $noteFolder -or "" -eq $noteFolder) {
Write-Host "フォルダが未指定です。"
return $false
}
# フォルダ存在チェック
$ifExistFolder = Test-Path $noteFolder
if (!$ifExistFolder) {
Write-Host ("指定フォルダがありません:" + $noteFolder)
return $false
}
return $true
}
function Get-TodayNoteName {
# 今日の日付を元にしたメモの名前を返す
$date = Get-Date -Format "yyyy_MM_dd"
return ($noteNamePrefix + $date + ".txt")
}
function New-Note {
# 今日用のメモを新規作成
$todayNoteName = Get-TodayNoteName
$todayNotePath = Join-Path $noteFolder -ChildPath $todayNoteName
New-Item -Path $todayNotePath
}
function Copy-LatestNote {
# 指定フォルダのファイルを取得
$notes = (Get-ChildItem $noteFolder -Filter *.txt | Sort-Object CreationTime -Descending)
if ($null -eq $notes -or 0 -eq $notes.Length) {
# 新規ファイルの作成
New-Note
Write-Host "新規メモを作成しました。"
}
else {
# 最新メモを複製
$latestNotePath = $notes[0].FullName
$todayNoteName = Get-TodayNoteName
$todayNotePath = Join-Path $noteFolder -ChildPath $todayNoteName
Copy-Item -Path $latestNotePath -Destination $todayNotePath
# コピー成否チェック
if (-not $?) {
Write-Host "今日のメモは複製済みです。"
}
else {
# 複製したものの日付プロパティを更新
$date = Get-Date
(Get-Item $todayNotePath).CreationTime = $date
(Get-Item $todayNotePath).LastWriteTime = $date
Write-Host ("最新メモを " + $todayNoteName + " として複製しました。")
}
}
}
function Main {
# 設定が適切かチェック
$isSettingCorrect = Test-Setting
if (!$isSettingCorrect) {
return
}
# 指定フォルダにあるメモの最新ファイルを複製
Copy-LatestNote
}
Main
Read-Host
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment