PowerShell arguments and encodings

Well, after fighting for an hour or two, I finally read a post explaining why my quotes were not passed around when invoking a script. Now that I'm using the -EncodedCommand attribute, everything works fine!

As the guys on the powershell team wrote about encoding conversion, I thought I'd provide two quick ones for those needing it, Url Encoding and Base64. Don't hesitate to add to your profile.

Note that I'm using LoadWithPartialName because I'm lazy and it still works on .net 2. Replace with proper LoadFrom or Load as needed.

[System.Reflection.Assembly]::LoadWithPartialName("System.Web") | out-null
function ConvertTo-UrlEncodedString([string]$dataToConvert)
{
    begin {
        function EncodeCore([string]$data) { return [System.Web.HttpUtility]::UrlEncode($data) }
    }
    process { if ($_ -as [string]) { EncodeCore($_) } }
    end { if ($dataToConvert) { EncodeCore($dataToConvert) } }
}
function ConvertFrom-UrlEncodedString([string]$dataToConvert)
{
    begin {
        function DecodeCore([string]$data) { return [System.Web.HttpUtility]::UrlDecode($data) }
    }
    process { if ($_ -as [string]) { DecodeCore($_) } }
    end { if ($dataToConvert) { DecodeCore($dataToConvert) } }
}
function ConvertTo-Base64EncodedString([string]$dataToConvert)
{
    begin {
        function EncodeCore([string]$data) { return [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($data)) }
    }
    process { if ($_ -as [string]) { EncodeCore($_) } }
    end { if ($dataToConvert) { EncodeCore($dataToConvert) } }
}
function ConvertFrom-Base64EncodedString([string]$dataToConvert)
{
    begin {
        function DecodeCore([string]$data) { return [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($data)) }
    }
    process { if ($_ -as [string]) { DecodeCore($_) } }
    end { if ($dataToConvert) { DecodeCore($dataToConvert) } }
}

 

Technorati Tags: , , ,

Ads

Comment