#######################################################
# 設定項目/ 必要に応じて変更
<#
$from_path = 遷移元パスを指定
$to_path = 遷移先パスを指定
$filenames = ファイル名を指定
#>
#######################################################
$from_path = "C:\Users\user\Desktop\あ"
$to_path = "C:\Users\user\Desktop\確認"
$filenames = "TEST.DMP", "TEST", "TESTsize"
# 変数
$username = $env:USERNAME
$hostname = hostname
$datetime = Get-Date -f 'yyyyMMddHHmmss'
$logdir = "$PSScriptRoot/log/"
$logfilename = "${username}-${hostname}-${datetime}-FileCopy.log"
# ログ記込み開始
Start-Transcript "${logdir}${logfilename}" -append
Write-Host @"
*********************************************************
*
* FileCopy Script / FileCopy.ps1
* バージョン : 1.0
* 作成者 : user
* 作成日 : 2024/07/16
* 更新者 :
* 更新日 :
*
"@ -ForeGroundColor green
try{
# コピー元のPath確認
if(-not (Test-Path -LiteralPath $from_path )){
Write-Host "[Error] $from_path は見つかりません。`r`n コピー元のディレクトリをご確認ください。"
exit
}
# コピー先のPath確認
# if(-not (Test-Path -LiteralPath $from_path )){
if(-not (Test-Path $to_path )){
Write-Host "[Error] $to_path は見つかりません。`r`n コピー先のディレクトリをご確認ください。"
exit
}
# 対象ファイを取得し、コピー先へコピー。対象ファイルが存在したい場合log
$filelists = Get-ChildItem -LiteralPath $from_path | Where-Object {$_.Name -In $filenames}
if($filelists){
$filelists | ForEach-Object {
$infile = $_.FullName
$outfile = $to_path + "\" + $_.Name + "_" + $datetime
Copy-Item -LiteralPath $infile -Destination $outfile -Recurse
Write-Host "[INFO] $infile から $outfile をコピーしました。"
}
}else {
Write-Host "[Error] $from_path で対象ファイルは見つかりません。`r`n 対象ファイルの存在をご確認ください。"
exit
}
} catch [Exception]{
Write-Host '[Error] ファイルコピーにエラーが発生しました。'
Write-Host $Error
}
try{
# コピー先のディレクトリで6世代以上保持し、最も日付が古いものは削除
$to_filenames = Get-ChildItem -LiteralPath $to_path | Select-Object @{Name="datetimes";Expression={$_.Name.Substring($_.Name.Length - 14, 14)}} , Name |
Sort-Object -Property { $_.datetimes} -Descending
$exclude_filenames = ($to_filenames | Select-Object -First (6 * $filenames.Length) ).Name
# Get-ChildItem -LiteralPath $to_path | Where-Object {$_.Name -notin $exclude_filenames } | Remove-Item
Remove-Item "${to_path}\*" -Exclude ${exclude_filenames} -Recurse
Write-Host "$(Get-Date -Format g) ${exclude_filenames} 以外ファイルを削除"
# "${username}-${hostname}-${datetime}-FileCop.log"以外の logファイルを削除
Remove-Item "${logdir}\*" -Exclude ${logfilename} -Recurse
Write-Host "$(Get-Date -Format g) ${logfilename} 以外ファイルを削除"
} catch [Exception]{
Write-Host '[Error] ファイル削除にエラーが発生しました。'
Write-Host $Error
}
# ログ出力終了
Stop-Transcript
コメント