markpy
markpy

Reputation: 21

Show all special characters / escaped characters in powershell

In python if you place a string inside of a list it displays all special characters when you display the list. Python example

With code in powershell we start with:

$data = Get-Clipboard

How would I get $data to reveal all of the special characters?

Upvotes: 2

Views: 1272

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 29033

There is no builtin way that I know of to do what Python does, you would have to code it yourself.

$Data | Format-Hex will show you the character codes in the string, in hexadecimal. That's not easy to read, but it is enough to distinguish different whitespace characters:

PS C:\> $data = "A`r`nZ"
PS C:\> $data |Format-Hex


           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   41 0D 0A 5A                                      A..Z

0D is char 13, carriage return. 0A is char 10, linefeed.

If you wanted to code it, something like this:

PS C:\> $translated = foreach ($char in $data.GetEnumerator()) {
  switch ($char) {
    "`0" { '`0' }
    "`a" { '`a' }
    "`b" { '`b' }
    "`e" { '`e' }
    "`f" { '`f' }
    "`n" { '`n' }
    "`r" { '`r' }
    "`t" { '`t' }
    "`v" { '`v' }
    default { $char }
  }
}

PS C:\> -join $translated
A`r`nZ

Taking the codes from the PowerShell tokenizer, what it will recognize inside double-quoted expandable strings as special characters, and turning them into single-quoted literal strings.

NB. not all of them can be turned back, I don't think. You could approach it differently with a regex to match non-printable control codes, or Unicode categories and try to cover more cases that way.

Upvotes: 3

Related Questions