Function Copy-TemplateFolder {
Param(
[string]$templateFolderPath, # テンプレートフォルダのパス
[string]$newFolderName # 新しいフォルダ名
)
# フォルダのコピーとリネーム処理
Try {
# 新しいフォルダのパスを生成
$newFolderPath = Join-Path -Path (Split-Path -Path $templateFolderPath -Parent) -ChildPath $newFolderName
# テンプレートフォルダを新しいフォルダにコピー
Copy-Item -Path $templateFolderPath -Destination $newFolderPath -Recurse -Force
# サブフォルダやファイルも別名でコピーする処理は既に上記のコピーで行われている
Write-Host "フォルダがコピーされました: $newFolderPath"
} Catch {
Write-Host "エラーが発生しました: $_"
}
}
Copy-TemplateFolder -templateFolderPath "C:\\TemplateFolder" -newFolderName "NewFolder"
Function Copy-TemplateFolder {
Param(
[string]$templateFolderPath, # テンプレートフォルダのパス
[string]$newFolderName, # 新しいフォルダ名
[hashtable]$renameRules # 名前変更のルール (キー: 変更前の文字列, 値: 変更後の文字列)
)
# フォルダのコピーとリネーム処理
Try {
# 新しいフォルダのパスを生成
$newFolderPath = Join-Path -Path (Split-Path -Path $templateFolderPath -Parent) -ChildPath $newFolderName
# テンプレートフォルダを新しいフォルダにコピー
Copy-Item -Path $templateFolderPath -Destination $newFolderPath -Recurse -Force
# フォルダ内の各ファイルとフォルダに対して、指定された名前変更ルールを適用
Get-ChildItem -Path $newFolderPath -Recurse | ForEach-Object {
# 現在のパス
$currentPath = $_.FullName
# 名前変更ルールを適用
foreach ($key in $renameRules.Keys) {
if ($currentPath -like "*$key*") {
$newPath = $currentPath -replace $key, $renameRules[$key]
Rename-Item -Path $currentPath -NewName $newPath
}
}
}
Write-Host "フォルダがコピーされ、名前が変更されました: $newFolderPath"
} Catch {
Write-Host "エラーが発生しました: $_"
}
}
以下の例では、C:\\TemplateFolder
を C:\\NewFolder
にコピーし、フォルダ内のファイル名やサブフォルダ名に含まれる特定の文字列を別の文字列に置換します。
Copy-TemplateFolder
関数の定義をPowerShellに入力します。
以下のコマンドを実行して、フォルダをコピーし、名前を変更します。
$renameRules = @{
"OldString1" = "NewString1";
"OldString2" = "NewString2"
}
Copy-TemplateFolder -templateFolderPath "C:\\TemplateFolder" -newFolderName "NewFolder" -renameRules $renameRules
このコマンドを実行すると、C:\\TemplateFolder
が C:\\NewFolder
にコピーされ、その中のファイルやフォルダ名に含まれる "OldString1"
は "NewString1"
に、"OldString2"
は "NewString2"
に置換されます。
Function Copy-TemplateFolder {
Param(
[string]$templateFolderPath, # テンプレートフォルダのパス
[string]$newFolderName, # 新しいフォルダ名
[hashtable]$renameRules # 名前変更のルール
)
# フォルダの存在確認
if (-not (Test-Path -Path $templateFolderPath)) {
Write-Host "指定されたテンプレートフォルダは存在しません: $templateFolderPath"
return
}
# フォルダのコピーとリネーム処理
Try {
# 新しいフォルダのパスを生成
$newFolderPath = Join-Path -Path (Split-Path -Path $templateFolderPath -Parent) -ChildPath $newFolderName
# テンプレートフォルダを新しいフォルダにコピー
Copy-Item -Path $templateFolderPath -Destination $newFolderPath -Recurse -Force
# フォルダ内の各ファイルとフォルダに対して、指定された名前変更ルールを適用
Get-ChildItem -Path $newFolderPath -Recurse | ForEach-Object {
# 現在のパス
$currentPath = $_.FullName
# 名前変更ルールを適用
foreach ($key in $renameRules.Keys) {
if ($currentPath -like "*$key*") {
$newPath = $currentPath -replace $key, $renameRules[$key]
Rename-Item -Path $currentPath -NewName $newPath
}
}
}
Write-Host "フォルダがコピーされ、名前が変更されました: $newFolderPath"
} Catch {
Write-Host "エラーが発生しました: $_"
}
}