powershell

Handling special characters in password string


I have a string. Sometimes it looks like this:

9xABp'}H9$G(@

While, sometimes it looks like this:

9xABp"}H9$G(@

I do not have any control over the character set used to generate the string, but I need to have Powershell stop complaining that the string cannot be parsed and to give me all of the characters.

$string = '9xABp'}H9$G(@'
$secure = ConvertTo-SecureString -String $string -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

That doesn't work, so I tried wrapping my string in double quotes, instead of single quotes.

$string = "9xABp'}H9$G(@"
$secure = ConvertTo-SecureString -String $string -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

That's fine, but $G is not included (replaced by a backslash) and what about when my string has a double quote inside?

I tried using [Regex]::Escape().

$string = "9xABp'}H9$G(@"
$secure = ConvertTo-SecureString -String ([Regex]::Escape($string)) -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

But $G is still missing. Another try, this time with double and single quotes on the outside.

$string = "'9xABp'}H9$G(@'"
$secure = ConvertTo-SecureString -String ([Regex]::Escape($string)) -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

What can I do here?


Solution

  • The PowerShell herestring exists for just such an occasion.

    $string = @"
    '9xABp'}H9$G(@'
    "@
    

    The @" and "@ characters have to be on their own line, but allow for any characters inside of them.

    Edit

    Thanks to Mike Klement for reminding me of the single quote variant, which should be used if your password might contain a $ or another character which has significance in PowerShell.

    $string = @'
    '9xABp'}H9$G(@'
    '@
    

    This works the same as the previous here-string but this one will not expand a variable, and is a better fit.