Skip to content

Instantly share code, notes, and snippets.

@yoshimov
Last active April 2, 2024 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoshimov/8f874be42059869f3624d870765e2720 to your computer and use it in GitHub Desktop.
Save yoshimov/8f874be42059869f3624d870765e2720 to your computer and use it in GitHub Desktop.
<# copilot prompt
テキストファイルに列挙したファイルのみを特定のフォルダにコピーするPowerShellのスクリプトを書いてください。
- コピーするファイル名は相対パスで列挙
- コピー元のフォルダはsourcePathに設定
- コピー先のフォルダはdestinationPathに設定
- コピーするファイル名を列挙したファイルのパスはfileListPathに設定
- ファイル名を列挙したファイルはUTF8で読み込む
- コピー中のファイルの情報を表示
- コピー先にファイルが存在する場合はコピーをスキップする
- コピー元のファイルは再帰的に検索する
- コピー元のファイルが存在しない場合はエラーを表示する
#>
# ファイルリストとディレクトリパスを定義
$sourcePath = "C:\Source"
$fileListPath = "file-list.txt"
$destinationPath = "D:\"
# ファイルリストをUTF-8で読み込み
$fileList = Get-Content $fileListPath -Encoding UTF8
# ファイルリスト内の各ファイルに対して処理
foreach ($relativePath in $fileList) {
# コピー元のフォルダ内を再帰的に検索
$filesToCopy = Get-ChildItem -Path $sourcePath -Recurse | Where-Object { $_.Name -match $relativePath }
# ファイルが見つからない場合はエラーを表示
if ($filesToCopy -eq $null) {
Write-Host "エラー: '$relativePath' に一致するファイルは '$sourcePath' 内に存在しません。"
continue
}
# 見つかったファイルをコピー先にコピー
foreach ($file in $filesToCopy) {
$destinationFile = Join-Path $destinationPath $file.Name
# コピー先にファイルが存在するか確認
if (Test-Path $destinationFile) {
Write-Host "'$file' は既に '$destinationPath' に存在します。スキップします。"
} else {
# ファイルをコピーし、進行状況を表示
Write-Host "'$file' を '$destinationPath' にコピー中..."
Copy-Item $file.FullName $destinationFile -Verbose
Write-Host "'$file' をコピーしました。"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment