使用 PowerShell 与 7zip 备份文件到阿里云盘

echo "Start:"

$paths = "E:\Repos", "E:\ReposStar"

$folders = @()

foreach ($path in $paths) {
    # 直接使用指定路径下的所有一级子目录
    $folders += Get-ChildItem -Path $path -Directory | ForEach-Object { $_.FullName }
}

$folders += "C:\Users\yiyun\Desktop"
$folders += "E:\Archived"
$folders += "E:\Books"
$folders += "E:\Dropbox"
$folders += "E:\Nextcloud"
$folders += "E:\School"
$folders += "D:\Program Portable"
$folders += "D:\Program Files\Scoop"

$cloudDestPath = "/加密备份"

$zipPassword = "your-zip-password"


foreach ($folderPath in $folders)
{
    # 获取文件夹名称
    $folderName = Split-Path $folderPath -Leaf

    # 去掉盘符: F:\Books\软件设计 -> \Books\软件设计
    $relativePath = Split-Path $folderPath -NoQualifier
    # \Books\软件设计 -> /Books/软件设计
    $relativePath = $relativePath.Replace('\', '/')

    # 创建压缩包名称
    $timestamp = Get-Date -Format 'yyyyMMddHHmmss'
    # $zipFileName = "$($folderName)-$($timestamp).zip"
    $zipFileName = "$($folderName)-$($timestamp).7z"

    # 获取父路径
    $parentPath = Split-Path $folderPath -Parent

    # 完整的压缩包路径
    $zipFilePath = Join-Path -Path $parentPath -ChildPath $zipFileName

    echo "Compress...: $zipFilePath"

    Try {
        # 执行压缩操作
        # 自带方式不能超过 2GB
        # Compress-Archive -Path $folderPath -DestinationPath $zipFilePath
        
        # scoop bucket add main
        # scoop install main/7zip
        # zip 不支持文件名加密
        # 7z a -tzip -p"$zipPassword" -mem=AES256 "$zipFilePath" "$folderPath"
        # -mhe=on 文件头(包括文件名)加密, 没有密码无法看到文件列表
        7z a -t7z -p"$zipPassword" -mhe=on "$zipFilePath" "$folderPath"
        
        echo "Compress success"

        echo "Uploading..."

        # https://120365.moeci.com/apps/AlipanCli
		coo alipan upload --from "$zipFilePath" --to "$cloudDestPath$relativePath/$zipFileName" --remote-drive-type resource

        echo "Upload success"
    } Catch {
        echo "An error occurred: $_"
        If (Test-Path $zipFilePath) {
            echo "Deleting incomplete zip file: $zipFilePath"
            Remove-Item $zipFilePath -Force
            echo "Delete success"
        }
        continue
    } Finally {
        # 无论成功还是失败, 都尝试执行的操作
        # 如果存在zip压缩包, 则删除
        If (Test-Path $zipFilePath) {
            echo "Deleting zip file: $zipFilePath"
            Remove-Item $zipFilePath -Force
            echo "Delete success"
        }
    }
}

echo "Finished"