You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell批量将.txt、.qc文件加密为.pgp格式的脚本优化求助

PowerShell 批量加密改名解决方案

核心调整原因

原脚本直接对全目录执行加密命令,未做单文件遍历和命名处理,因此无法批量操作,也不能替换原有后缀。

修正后完整脚本

# 配置路径参数
$_SourcePath = "\\Server1\Location1\"
$_TempPath = "\\Server1\Location2\"
$_DestinationPath = "\\Server2\Location1\"
$PgpKeyPath = "\\server3\location1\Enycrption key.asc"
# 支持的源文件后缀
$SupportExts = @(".txt", ".qc")

# 1. 移动所有符合条件的源文件到临时目录
Get-ChildItem -Path $_SourcePath -File | Where-Object { $_.Extension -in $SupportExts } | Move-Item -Destination $_TempPath -Force

# 2. 批量遍历临时目录内的文件,逐一对每个文件加密并重命名
Get-ChildItem -Path $_TempPath -File | Where-Object { $_.Extension -in $SupportExts } | ForEach-Object {
    # 生成加密后的文件名:去掉原有后缀,加上.pgp
    $EncryptedFileName = $_.BaseName + ".pgp"
    $EncryptedFilePath = Join-Path -Path $_TempPath -ChildPath $EncryptedFileName
    # 执行PGP加密,指定输出路径
    ConvertTo-PgpEncryptedFile -Path $_.FullName -Key $PgpKeyPath -OutputPath $EncryptedFilePath
    # 加密完成后删除未加密的原临时文件,不需要可注释该行
    Remove-Item -Path $_.FullName -Force
}

# 3. 移动所有加密后的pgp文件到目标Server2
Move-Item -Path (Join-Path $_TempPath "*.pgp") -Destination $_DestinationPath -Force

兼容适配说明

如果你使用的ConvertTo-PgpEncryptedFile命令不支持-OutputPath参数,默认会在原文件路径生成原文件名.原后缀.pgp格式的文件,可以把第二步加密部分的逻辑替换为以下内容,同样可以实现后缀替换:

Get-ChildItem -Path $_TempPath -File | Where-Object { $_.Extension -in $SupportExts } | ForEach-Object {
    # 执行默认加密
    ConvertTo-PgpEncryptedFile -Path $_.FullName -Key $PgpKeyPath
    # 重命名加密文件,去掉中间的原始后缀
    $DefaultEncryptedPath = $_.FullName + ".pgp"
    $TargetEncryptedPath = Join-Path -Path $_TempPath -ChildPath ($_.BaseName + ".pgp")
    Rename-Item -Path $DefaultEncryptedPath -Destination $TargetEncryptedPath -Force
    # 删除未加密的原临时文件
    Remove-Item -Path $_.FullName -Force
}

内容的提问来源于stack exchange,提问作者JFlour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 09:09:02