powershell上移文件夹下的所有文件
将某个文件夹(例如 .\OldFolder
)下的所有文件和子文件夹“上移”到其父目录中,然后 删除这个空的 OldFolder
# 提示用户输入要上移的文件夹路径
$folderPath = Read-Host "请输入要上移内容的文件夹完整路径(例如:C:\Parent\OldFolder)"
# 去除首尾空格
$folderPath = $folderPath.Trim()
# 验证路径是否存在
if (-not (Test-Path -Path $folderPath -PathType Container)) {
Write-Error "错误:路径不存在或不是一个文件夹:$folderPath"
exit 1
}
# 获取父目录
$parentDir = Split-Path -Parent $folderPath
$folderName = Split-Path -Leaf $folderPath
Write-Host "即将把文件夹 '$folderName' 中的所有内容移动到父目录:`n $parentDir`n"
# 列出将要移动的项目(可选预览)
$items = Get-ChildItem -Path $folderPath -Force
if ($items) {
Write-Host "将移动以下 $($items.Count) 个项目:"
$items | ForEach-Object { Write-Host " - $($_.Name)" }
} else {
Write-Host "文件夹为空,将直接删除。"
}
# 确认操作
$confirm = Read-Host "是否继续?(Y/N)"
if ($confirm -notmatch '^[Yy]$') {
Write-Host "操作已取消。"
exit 0
}
# 执行移动
if ($items) {
foreach ($item in $items) {
$destPath = Join-Path -Path $parentDir -ChildPath $item.Name
if (Test-Path -Path $destPath) {
Write-Warning "目标已存在,跳过:$($item.Name)"
# 如需覆盖,可取消下面两行注释
# Remove-Item -Path $destPath -Recurse -Force
# Move-Item -Path $item.FullName -Destination $parentDir -Force
} else {
Move-Item -Path $item.FullName -Destination $parentDir
Write-Host "已移动:$($item.Name)"
}
}
}
# 删除原文件夹
Remove-Item -Path $folderPath -Recurse -Force
Write-Host "`n✅ 操作完成!文件夹 '$folderName' 已被删除。"