Last active
January 7, 2019 03:35
-
-
Save steviecoaster/55c109c5497b225cdeff20ffcf294d30 to your computer and use it in GitHub Desktop.
Convert a string to Base64
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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