ファイル名を指定して、フォルダーAからフォルダーB に指定したファイルを移動するプログラムを作成しています。
# パラメータ定義
param (
[Parameter(Mandatory=$true)]
[string]$sourceFolder, # 移動元フォルダーパス
[Parameter(Mandatory=$true)]
[string]$destinationFolder, # 移動先フォルダーパス
[Parameter(Mandatory=$true)]
[string]$fileListPath # ファイルリストのテキストファイルパス
)
# エラーハンドリング設定
$ErrorActionPreference = "Stop"
function Move-Files {
try {
# フォルダーの存在確認
if (-not (Test-Path $sourceFolder)) {
throw "Source folder does not exist: $sourceFolder"
}
if (-not (Test-Path $destinationFolder)) {
Write-Host "Creating destination folder: $destinationFolder"
New-Item -ItemType Directory -Path $destinationFolder | Out-Null
}
# ファイルリストの読み込み
$files = Get-Content $fileListPath
# 移動処理の実行
$successCount = 0
$errorCount = 0
foreach ($file in $files) {
$sourcePath = Join-Path $sourceFolder $file
$destinationPath = Join-Path $destinationFolder $file
if (Test-Path $sourcePath) {
try {
Move-Item -Path $sourcePath -Destination $destinationPath -Force
Write-Host "Successfully moved: $file" -ForegroundColor Green
$successCount++
}
catch {
Write-Host "Error moving file: $file - $($_.Exception.Message)" -ForegroundColor Red
$errorCount++
}
}
else {
Write-Host "File not found: $file" -ForegroundColor Yellow
$errorCount++
}
}
# 結果の表示
Write-Host "`nMoving completed!" -ForegroundColor Cyan
Write-Host "Successfully moved: $successCount files" -ForegroundColor Green
Write-Host "Errors encountered: $errorCount files" -ForegroundColor Red
}
catch {
Write-Host "An error occurred: $($_.Exception.Message)" -ForegroundColor Red
exit 1
}
}
# スクリプトの実行
Move-Files
使い方は以下の通りです。
まず、移動したいファイル名のリストをテキストファイル(例:filelist.txt)に保存します。
スクリプトを実行します:
powershellCopy.\move-files.ps1 -sourceFolder "C:\FolderA" -destinationFolder "D:\FolderB" -fileListPath "C:\filelist.txt"
0 件のコメント:
コメントを投稿