如何用PowerShell批量解密GPG文件并输出到指定目录重命名?
解决GPG文件批量解密并重命名的问题
修正后的PowerShell代码
你的原代码问题出在没有正确执行路径拼接表达式,而且没传入文件的完整路径给gpg命令。下面是修正后的版本:
$in = ".\img.gpg\" $out = ".\img\" # 确保输出目录存在,不存在则创建 if (-not (Test-Path -Path $out)) { New-Item -ItemType Directory -Path $out | Out-Null } # 只处理目录下的文件,排除子目录 Get-ChildItem -Path $in -File | ForEach-Object { # 拼接输出文件路径,移除.gpg扩展名 $outputFilePath = Join-Path -Path $out -ChildPath $_.Name.Substring(0, $_.Name.Length - 4) # 调用gpg解密,传入原文件的完整路径 gpg -d -o $outputFilePath $_.FullName }
PowerShell脚本结构基础教程
参数传递
- 脚本参数定义:用
param()块在脚本开头定义参数,让脚本更灵活。示例:
param( [Parameter(Mandatory=$true)] # 设置为必填参数 [string]$InputDirectory, [Parameter(Mandatory=$true)] [string]$OutputDirectory ) # 后续代码直接使用$InputDirectory和$OutputDirectory变量
调用脚本时:.\DecryptGpg.ps1 -InputDirectory ".\img.gpg" -OutputDirectory ".\img"
- 管道参数处理:如果要让脚本支持管道输入,用
process块接收管道对象:
param( [Parameter(ValueFromPipeline=$true)] [System.IO.FileInfo]$File ) process { # 处理每个通过管道传来的文件 $outputPath = Join-Path -Path $OutputDirectory -ChildPath $File.Name.Substring(0, $File.Name.Length -4) gpg -d -o $outputPath $File.FullName }
调用方式:Get-ChildItem ".\img.gpg" -File | .\DecryptGpg.ps1 -OutputDirectory ".\img"
流程控制
- 循环
- ForEach-Object:适合管道场景,逐个处理管道传来的对象(就是你原代码用的方式)
- foreach集合循环:适合直接遍历本地集合,性能略高:
$files = Get-ChildItem -Path $in -File foreach ($file in $files) { # 针对$file执行解密逻辑 }
- for计数循环:适合需要按序号循环的场景:
for ($i=0; $i -lt 10; $i++) { Write-Host "当前序号:$i" }
- 分支
- if/else条件判断:处理基础分支逻辑:
if (Test-Path -Path $out) { Write-Host "输出目录已存在" } else { New-Item -ItemType Directory -Path $out }
- switch多条件判断:处理多分支场景更简洁:
$extension = $_.Extension switch ($extension) { ".gpg" { # 执行GPG文件解密逻辑 } ".zip" { # 执行ZIP文件处理逻辑 } default { Write-Host "不支持的文件类型:$extension" } }
内容的提问来源于stack exchange,提问作者Erik Itter
相关产品推荐
相关产品推荐

