Created
May 28, 2019 18:32
-
-
Save IISResetMe/b5db0a4540d8056edacb8d31c5a1e6be to your computer and use it in GitHub Desktop.
System.Text.Encoding converter to easy argument conversion
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 PSTextEncodingConverter : PSTypeConverter { | |
hidden | |
[hashtable] | |
$ConversionTable = @{ | |
'ASCII' = [System.Text.Encoding]::ASCII | |
'ANSI' = [System.Text.Encoding]::ASCII | |
'UTF7' = [System.Text.Encoding]::UTF7 | |
'UTF-7' = [System.Text.Encoding]::UTF7 | |
'UTF8' = [System.Text.Encoding]::UTF8 | |
'UTF-8' = [System.Text.Encoding]::UTF8 | |
'Unicode' = [System.Text.Encoding]::Unicode | |
'UTF16LE' = [System.Text.Encoding]::Unicode | |
'LittleEndianUnicode' = [System.Text.Encoding]::Unicode | |
'UTF16BE' = [System.Text.Encoding]::BigEndianUnicode | |
'BigEndianUnicode' = [System.Text.Encoding]::BigEndianUnicode | |
'UTF32' = [System.Text.Encoding]::UTF32 | |
'UTF-32' = [System.Text.Encoding]::UTF32 | |
'Default' = [System.Text.Encoding]::Default | |
} | |
[bool] | |
CanConvertFrom([object]$value, [type]$targetType) { | |
return ( | |
$this.IsEncodingType($targetType) | |
) -and ( | |
( | |
$value -is $targetType | |
) -or ( | |
( | |
$value -is [string] | |
) -and ( | |
"$value" -in $this.ConversionTable.Keys | |
) | |
) | |
) | |
} | |
[object] | |
ConvertFrom([object]$value, [Type]$targetType, [IFormatProvider]$format, [bool]$ignoreCase) { | |
if ($value -is $targetType) { | |
return $value | |
} | |
if ($this.ConversionTable.Contains("$value")) { | |
return $this.ConversionTable["$value"] | |
} | |
throw "Failed to convert '$value' to [$($targetType.FullName)]." | |
} | |
[bool] | |
CanConvertTo([object]$value, [Type]$targetType) { | |
return $this.CanConvertFrom($value, $targetType) | |
} | |
[object] | |
ConvertTo([object]$value, [Type]$targetType, [IFormatProvider]$format, [bool]$ignoreCase) { | |
return $this.ConvertFrom($value, $targetType, $format, $ignoreCase) | |
} | |
[bool] | |
IsEncodingType([type]$targetType) { | |
$type = $targetType | |
do { | |
if ($type -eq [Encoding]) { | |
return $true | |
} | |
} while (($type = $type.BaseType) -ne $null) | |
return $false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment