Powershell 中 Base64 解码的替代方案

Tan*_*nik 2 windows postgresql powershell kubernetes minikube

我正在按照指南将数据库连接到 kubernetes: https: //itnext.io/basic-postgres-database-in-kubernetes-23c7834d91ef

在 Windows 10 64 位上安装 Kubernetes (minikube) 后: https: //minikube.sigs.k8s.io/docs/start/

我遇到“base64”问题,其中数据库尝试连接并存储密码。因为 PowerShell 无法识别它。我想知道是否有人有任何想法如何解决这个问题并仍然使用 Windows 或其他方法,使我能够继续本指南的其余部分?

错误代码:

base64 : The term 'base64' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:131
+ ... postgresql -o jsonpath="{.data.postgresql-password}" | base64 --decod ...
+                                                            ~~~~~~
    + CategoryInfo          : ObjectNotFound: (base64:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

export : The term 'export' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ export POSTGRES_PASSWORD=$(kubectl get secret --namespace default pos ...
+ ~~~~~~
    + CategoryInfo          : ObjectNotFound: (export:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
Run Code Online (Sandbox Code Playgroud)

Windows Powershell 错误消息

Mat*_*sen 6

Mac OS 和某些 *nix 发行版中的clibase64在 Windows 上不可用。

可以编写一个名为的小函数base64来模仿 unix 工具的行为base64

function base64 {
  # enumerate all pipeline input
  $input |ForEach-Object {
    if($MyInvocation.UnboundArguments -contains '--decode'){
      # caller supplied `--decode`, so decode 
      $bytes = [convert]::FromBase64String($_)
      [System.Text.Encoding]::ASCII.GetString($bytes)
    } else {
      # default mode, encode ascii text as base64
      $bytes = [System.Text.Encoding]::ASCII.GetBytes($_)
      [convert]::ToBase64String($bytes)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这应该可以作为 ASCII/UTF7 文本和 base64 之间转换的直接替代:

PS ~> 'Hello, World!' |base64 --encode
SGVsbG8sIFdvcmxkIQ==
PS ~> 'Hello, World!' |base64 --encode |base64 --decode
Hello, World!
Run Code Online (Sandbox Code Playgroud)

要与现有脚本一起使用,请在执行其他脚本之前使用 shell 中的函数定义简单地对脚本进行点源:

PS ~> . .\path\to\base64.ps1
Run Code Online (Sandbox Code Playgroud)

上面的内容也适用于脚本。如果您有一个多行粘贴感知 shell(带有 PSReadLine 的 Windows 默认控制台主机应该没问题),您也可以将函数定义直接粘贴到提示符中:)