1

I want to convert cmdlets to windows-1251 encoding so that Russian characters are displayed on the output.

My code:

$result = 'Invoke-RestMethod -Method "Post" -Uri https://ntfy.sh/most -Body "Hello 123 Привет" -UseBasicParsing'

$rus_result =  [System.Text.Encoding]::GetEncoding('windows-1251').GetString([Byte[]]$result)

PowerShell Errors:

InvalidArgument: Cannot convert value "Invoke-RestMethod -Method >"Post" -Uri https://ntfy.sh/most -Body "Hello 123 Привет" ->UseBasicParsing" to type "System.Byte[]". Error: "Cannot convert value >"Invoke-RestMethod -Method "Post" -Uri https://ntfy.sh/most -Body >"Hello 123 Привет" -UseBasicParsing" to type "System.Byte". Error: >"Input string was not in a correct format."" enter image description here

mklement0
  • 382,024
  • 64
  • 607
  • 775
kiki
  • 11
  • 3
  • `'Invoke-RestMethod ...'` is a verbatim _string literal_, so whatever is inside `'...'` is assigned _as-is_ to `$result`. If you want to _execute a command_, remove the `'` chars. – mklement0 Oct 26 '22 at 22:21
  • @mklement0 I want to execute the command after converting Russian characters, otherwise they are replaced with question marks. – kiki Oct 26 '22 at 22:29
  • Character encoding is an unrelated problem. – mklement0 Oct 26 '22 at 22:40
  • I just don't understand how to do it right. – kiki Oct 26 '22 at 22:46
  • You'll need to provide more information about what you're trying to do, and what the expected results are: what character encoding does the target web service expect? What is the character encoding it uses for its responses? – mklement0 Oct 26 '22 at 22:51
  • Everything happens in UTF-8 – kiki Oct 26 '22 at 22:59
  • Try `-Content 'text/plain; charset=utf-8'` for _sending_. On _receiving_, [`Invoke-RestMethod`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/invoke-restmethod) never reports _raw bytes_, from what I can tell. If you need to _reinterpret_ a misdecoded string, use the technique described in [this answer](https://stackoverflow.com/a/53034595/45375). – mklement0 Oct 26 '22 at 23:06
  • Also note that .NET strings use UTF-16LE, i.e. they're capable of representing _all_ Unicode characters. However, some Unicode characters may not _render_ correctly, in regular Windows console windows (provided by `conhost.exe`). You won't have that problem if you use [Windows Terminal](https://aka.ms/windowsterminal) instead. – mklement0 Oct 26 '22 at 23:11

0 Answers0