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

如何编写带参数的PowerShell Base64编解码器脚本?

Base64编解码器脚本实现与问题修复

直接给你可运行的完整脚本,同时拆解核心逻辑,解决你解码失败的问题:

<#
.SYNOPSIS
Base64编解码器:支持字符串/文件的编码、解码,输出到控制台或指定文件
#>

param(
    [Parameter(Mandatory=$true, ParameterSetName="EncodeString")]
    [Parameter(Mandatory=$true, ParameterSetName="DecodeString")]
    [string]$InputString,

    [Parameter(Mandatory=$true, ParameterSetName="EncodeFile")]
    [Parameter(Mandatory=$true, ParameterSetName="DecodeFile")]
    [string]$f,

    [Parameter(Mandatory=$true, ParameterSetName="EncodeString")]
    [Parameter(Mandatory=$true, ParameterSetName="EncodeFile")]
    [switch]$e,

    [Parameter(Mandatory=$true, ParameterSetName="DecodeString")]
    [Parameter(Mandatory=$true, ParameterSetName="DecodeFile")]
    [switch]$d,

    [string]$p
)

# 编码逻辑
if ($e) {
    $bytes = if ($f) {
        # 直接读取文件字节,避免文本编码干扰
        Get-Content -Path $f -Raw -Encoding Byte
    } else {
        # 统一用UTF-8将字符串转为字节数组
        [System.Text.Encoding]::UTF8.GetBytes($InputString)
    }
    $base64Result = [System.Convert]::ToBase64String($bytes)
    
    # 输出到文件或控制台
    if ($p) {
        $base64Result | Out-File -Path $p -Encoding UTF8
    } else {
        Write-Output $base64Result
    }
}

# 解码逻辑
if ($d) {
    $rawInput = if ($f) {
        # 读取文件并移除所有换行符(Base64不允许换行)
        Get-Content -Path $f -Raw | ForEach-Object { $_ -replace "\r?\n", "" }
    } else {
        $InputString -replace "\r?\n", ""
    }

    try {
        $bytes = [System.Convert]::FromBase64String($rawInput)
        $decodedResult = [System.Text.Encoding]::UTF8.GetString($bytes)
        
        # 输出处理
        if ($p) {
            $decodedResult | Out-File -Path $p -Encoding UTF8
        } else {
            Write-Output $decodedResult
        }
    } catch {
        Write-Error "解码失败:非法Base64格式或内容错误,详情:$_"
        exit 1
    }
}

核心问题修复说明

你解码失败大概率是这两个原因:

  1. Base64字符串含换行符:从文件读取或复制的Base64常带自动换行,FromBase64String会直接报错,脚本中通过-replace "\r?\n", ""强制移除所有换行
  2. 编码/解码字符集不统一:如果编码用了系统默认编码(比如UTF-16),解码用UTF-8就会乱码,脚本统一使用UTF-8保证一致性

使用示例

  1. 编码字符串到控制台:
.\Base64Codec.ps1 -e -InputString "测试Base64编码"
  1. 解码Base64到文件:
.\Base64Codec.ps1 -d -InputString "5rWL6K+VQmFzZTY057yW56CB" -p .\解码结果.txt
  1. 编码文件内容:
.\Base64Codec.ps1 -e -f .\原始文件.txt -p .\编码结果.txt
  1. 解码Base64文件:
.\Base64Codec.ps1 -d -f .\编码结果.txt

常见排查点

  • 若解码报"无效Base64字符":检查输入是否有空格、特殊字符,脚本已处理换行,其他无效字符需手动清理
  • 若解码后乱码:确认原内容编码,若为GB2312等非UTF-8编码,将脚本中[System.Text.Encoding]::UTF8替换为对应编码(如[System.Text.Encoding]::GetEncoding("GB2312"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:15:32