2

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?

markpy
  • 21
  • 1
  • Does this answer your question? [Get-Content and show control characters such as \`r - visualize control characters in strings](https://stackoverflow.com/questions/27233342/get-content-and-show-control-characters-such-as-r-visualize-control-character) and/or [Does there exists a PowerShell Escape function for Special Characters](https://stackoverflow.com/a/68132665/1701026) – iRon Jan 14 '22 at 08:04

1 Answers1

3

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.

TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87