当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 如何在 PowerShell 中将 Base64 字符串转换为文本?

作者:精品下载站 日期:2024-12-14 05:20:24 浏览:13 分类:玩电脑

如何在 PowerShell 中将 Base64 字符串转换为文本?


最近,PowerShell开发团队有人让我在Powershell中将Base64字符串转换为文本。我解释了如何使用各种方法来做到这一点。在本教程中,我将通过示例向您展示如何在 PowerShell 中将 Base64 字符串转换为文本。

要在 PowerShell 中将 Base64 字符串转换为文本,可以使用 [System.Convert]::FromBase64String() 方法。此方法将 Base64 字符串解码为字节数组,然后可以使用 [System.Text.Encoding]::UTF8.GetString() 将其转换为可读的文本字符串。例如,给定一个 Base64 字符串 $base64String="SGVsbG8gV29ybGQh",您可以使用以下方法对其进行解码:

$bytes = [System.Convert]::FromBase64String($base64String)
$text = [System.Text.Encoding]::UTF8.GetString($bytes)
Write-Output $text

这将输出“Hello World!”。

PowerShell 中的 Base64 编码是什么?

Base64 编码是一种通过将二进制数据转换为 radix-64 表示形式将二进制数据编码为 ASCII 字符串格式的方法。每个 Base64 数字恰好代表 6 位数据。这种编码通常用于各种应用程序,包括通过 MIME 发送电子邮件、以 XML 或 JSON 存储复杂数据以及在 HTML 或 CSS 中嵌入图像数据。

在 PowerShell 中将 Base64 字符串转换为文本

现在,让我通过示例向您展示如何在 PowerShell 中使用各种方法将 Base64 字符串转换为文本。

方法 1:使用 [System.Convert]::FromBase64String()

在 PowerShell 中解码 Base64 字符串的最佳方法是使用 [System.Convert]::FromBase64String() 方法。此方法将 Base64 编码的字符串转换回字节数组,然后可以将其转换为可读的文本字符串。

这是一个例子。

# Base64 encoded string
$base64String = "SGVsbG8gV29ybGQh"

# Decode Base64 string to byte array
$bytes = [System.Convert]::FromBase64String($base64String)

# Convert byte array to text
$text = [System.Text.Encoding]::UTF8.GetString($bytes)

# Output the text
Write-Output $text

在此示例中,Base64 字符串 SGVsbG8gV29ybGQh 被解码为 Hello World!

我使用 VS code 执行上述 PowerShell 脚本后,您可以在下面的屏幕截图中看到输出。

[玩转系统] 如何在 PowerShell 中将 Base64 字符串转换为文本?

检查如何在 PowerShell 中将文件转换为 Base64?

方法二:使用Base64模块

现在,我向您展示另一种方法:使用 Base64 模块,它提供了一种更简化的方法来编码和解码 Base64 字符串。

首先,如果您还没有安装该模块,则需要安装:

Install-Module -Name Base64

这是一个完整的示例,可以更好地理解它。

# Import the Base64 module
Import-Module Base64

# Base64 encoded string
$base64String = "SGVsbG8gV29ybGQh"

# Decode Base64 string
$text = $base64String | ConvertFrom-Base64

# Output the text
Write-Output $text

查看如何在 PowerShell 中将字符串转换为 JSON?

方法三:使用自定义函数

您还可以创建自己的函数来在 PowerShell 中解码 Base64 字符串。这对于添加附加功能或自定义日志记录非常有用。

这是一个例子。

function Decode-Base64String {
    param (
        [string]$base64String
    )

    # Decode Base64 string to byte array
    $bytes = [System.Convert]::FromBase64String($base64String)

    # Convert byte array to text
    $text = [System.Text.Encoding]::UTF8.GetString($bytes)

    return $text
}

# Base64 encoded string
$base64String = "SGVsbG8gV29ybGQh"

# Decode using custom function
$text = Decode-Base64String -base64String $base64String

# Output the text
Write-Output $text

我执行了上面的脚本,您可以在下面的屏幕截图中看到输出:

[玩转系统] 如何在 PowerShell 中将 Base64 字符串转换为文本?

结论

在本教程中,我将向您展示如何使用不同的方法在 PowerShell 中将 Base64 字符串转换为文本,例如使用 [System. Convert]::FromBase64String()、使用Base64模块等。我还解释了如何创建自定义函数以在PowerShell中将Base64字符串转换为文本。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯