Skip to content

Instantly share code, notes, and snippets.

@steviecoaster
Last active January 7, 2019 03:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steviecoaster/55c109c5497b225cdeff20ffcf294d30 to your computer and use it in GitHub Desktop.
Save steviecoaster/55c109c5497b225cdeff20ffcf294d30 to your computer and use it in GitHub Desktop.
Convert a string to Base64
using namespace System.Management.Automation
using namespace System.Text
class EncodingTransformAttribute : ArgumentTransformationAttribute {
[object] Transform([EngineIntrinsics]$engineIntrinsics, [object] $inputData) {
switch ($inputdata) {
{ $_ -is [System.Text.Encoding]} {
return $_
}
{ $_ -is [String]} {
if ( $_ -in ([Encoding] | Get-Member -Static -MemberType Property).Name ) {
return [System.Text.Encoding]::$_
}
elseif ($_ -in [System.Text.Encoding]::GetEncodings().Name) {
return [System.Text.Encoding]::GetEncoding($_)
}
}
}
throw [ArgumentTransformationMetadataException]::new()
}
}
function ConvertTo-Base64 {
<#
.SYNOPSIS
Converts a human-readable string to Base64
.PARAMETER String
The string to encode in Base64
.EXAMPLE
ConvertTo-Base64 -String "The lazy log floats in the river"
.EXAMPLE
"Some people just like to watch the world burn" | ConvertTo-Base64
#>
[cmdletBinding()]
param(
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[String]
$String,
[Parameter()]
[ArgumentCompleter(
{
param($Command, $Parameter, $Encoding, $CommandAst, $FakeBoundParams)
$ValidEncodings = ([Encoding] | Get-Member -Static -MemberType Property).Name + [System.Text.Encoding]::GetEncodings().Name | Sort-Object
if(!$Encoding){
return $ValidEncodings
}
else {
return $ValidEncodings.Where{ $_.StartsWith($Encoding) }
}
}
)]
[EncodingTransformAttribute()]
[Encoding]
$Encoding
)
begin {}
process {
$Bytes = $Encoding.GetBytes($String)
$EncodedText =[Convert]::ToBase64String($Bytes)
$EncodedText
}
end {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment