r/PowerShell • • Feb 16 '26

Any advice on this script?

I've been playing around in Powershell and would like to get some advice on these two scripts I wrote. I've been trying different ParameterSets to see how they work. I also noticed that there's no native convert to / from Base64 / Hex Cmdlets so I thought to make my own.

#region ConvertTo-Type
Function ConvertTo-Type {
    [CmdletBinding( DefaultParameterSetName = 'Base64' )]
        param (
            [Parameter( Mandatory         = $true,
                        Position          = 0,
                        ValueFromPipeline = $true )]
            [string]$Value,

            [Parameter( ParameterSetName  = 'Base64' )]
            [switch]$Base64,

            [Parameter( ParameterSetName  = 'Hex' )]
            [switch]$Hex

        )

$bytes = [System.Text.Encoding]::UTF8.GetBytes($Value)

    Write-Verbose @"

    $Value will be encoded UTF8.

"@

$encoding = switch ($PSCmdlet.ParameterSetName) {

    Base64  { [convert]::ToBase64String($bytes) }
    Hex     { [convert]::ToHexString($bytes) }
    Default { Throw "Value not selected!" }

}

    Write-Verbose @"

    Converting to $($PSCmdlet.ParameterSetName).

"@

$encoding

} # End Function
#endregion

#region ConvertFrom-Type
Function ConvertFrom-Type {
    [CmdletBinding( DefaultParameterSetName = 'Base64' )]
        param (
            [Parameter( Mandatory         = $true,
                        Position          = 0,
                        ValueFromPipeline = $true )]
            [string]$Value,

            [Parameter( ParameterSetName  = 'Base64' )]
            [switch]$Base64,

            [Parameter( ParameterSetName  = 'Hex' )]
            [switch]$Hex

        )

$decoding = switch ($PSCmdlet.ParameterSetName) {

    Base64  { [convert]::FromBase64String($Value) }
    Hex     { [convert]::FromHexString($Value) }
    Default { Throw "Value not selected!" }

}

    Write-Verbose @"

    Converting to $($PSCmdlet.ParameterSetName).

"@

$text = [System.Text.Encoding]::UTF8.GetString($decoding)

    Write-Verbose @"

    $decoding will be decoded UTF8.

"@

$text

} # End Function
#endregion

Thoughts? Best practices? I didn't write up or include help so it would be shorter.

9 Upvotes

18 comments sorted by

View all comments

Show parent comment

1

u/I_see_farts Feb 17 '26

Thank you for this write up.

I'm both excited to dig into this more and overwhelmed by how advanced Powershell can get. (More the former than the latter!)