runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

PowerShell将我的文档、图片、视频等目录复制备份到D盘

PowerShell将我的文档、图片、视频等目录复制备份到D盘

 

1.右键开始菜单-终端(管理员),执行下边命令:

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

WIN10是右键开始菜单- Windows PowerShell(管理员)

2.开始菜单里搜索“Windows PowerShell ISE”,打开后,新建一个文档,把下边内容复制进去,然后保存,例如:“D:\aa.ps1”

 

# 将我的文档、图片、视频等目录复制到D盘 (前提是没改过映射)
# 配置目标磁盘根路径(可修改此处)
$targetDrive = "D:"
$targetRoot = Join-Path -Path $targetDrive -ChildPath "\"

# 定义用户目录映射关系

$folderMappings = @{
    "Documents"       = "我的文档"
    "Videos"       = "我的视频"
    "Pictures"       = "我的图片"    
    "Downloads"       = "我的下载"
    "Music"       = "我的音乐"
}

# 获取当前用户目录
$userProfile = [Environment]::GetFolderPath("UserProfile")

# 先把各文件夹内容复制到目标目录
Write-Host "--  准备复制文件夹 --"
foreach ($sourceFolder in $folderMappings.Keys) {
    $targetFolderName = $folderMappings[$sourceFolder]
    # C:\Users\jk\Documents
    $sourcePath = Join-Path -Path $userProfile -ChildPath $sourceFolder
    Write-Host "--  源目录: $sourcePath"
    # D:\我的文档
    $targetPath = Join-Path -Path $targetRoot -ChildPath $targetFolderName
    Write-Host "--目标目录: $targetPath"
     

    try {
        # 创建目标文件夹(如果不存在)
        if (-not (Test-Path -Path $targetPath)) {
            New-Item -Path $targetPath -ItemType Directory -Force | Out-Null
            Write-Host "已创建目标文件夹: $targetPath"
        }
         
        # 复制文件(如果源文件夹存在)
        if (Test-Path -Path $sourcePath) {
            # 使用robocopy确保复制所有内容(包括隐藏文件)
            Write-Host "准备把 $sourcePath 目录中的内容复制到 $targetPath"
          #  Write-Host "按回车继续执行"
          #  Pause
            robocopy $sourcePath $targetPath /E /R:0 /W:0 /NFL /NDL /XF desktop.ini
            Write-Host "已复制 $sourcePath 到 $targetPath"
        }       
    }
    catch {
        Write-Error "处理 $sourceFolder 时出错: $_"
    }
}
 

Write-Host "所有操作完成!" -ForegroundColor Green
Pause

 

其中:$targetDrive = "D:"  ,盘根据你的实际情况修改。

 

3.右键aa.ps1 - 使用 PowerShell 执行。

 

posted on 2026-04-02 11:25  runliuv  阅读(5)  评论(0)    收藏  举报