1

when i exec command in powershell:

psql --command "\encoding" "host=XXX port=XXX user=XXX password=XXX dbname=postgres"

Output:

gbk

when i exec command in powershell:

$a=psql --command "\encoding" "host=XXX port=XXX user=XXX password=XXX dbname=postgres"
Write-Output $a

Now the output is different:

utf-8

this why?

mklement0
  • 382,024
  • 64
  • 607
  • 775
zuker
  • 21
  • 3
  • I think you meen `encoding`, not `enconding`.. – Theo Aug 01 '22 at 13:18
  • i has been modified,thank you – zuker Aug 01 '22 at 13:22
  • Just fix your typo and see the result – Theo Aug 01 '22 at 13:23
  • I was very confused to get this result – zuker Aug 01 '22 at 13:27
  • Or I want to know the right way to write it – zuker Aug 01 '22 at 13:29
  • It looks like [`psql`](https://www.postgresguide.com/utilities/psql/) adjusts its character encoding based on whether its stdout prints directly to the console (terminal) or is connected to a pipe (which is what happens behind the scenes with `$a=...`). Note that if the output is indeed UTF-8 in that case, you need to (temporarily set `[Console]::OutputEncoding = [System.Text.Utf8Encoding]::new()` first - see [this answer](https://stackoverflow.com/a/35980675/45375) (middle section) for details. – mklement0 Aug 01 '22 at 18:57
  • Thank you very much for answering my question。when i use " | Tee-Object a.log ", Still get the wrong answer "UTF-8" – zuker Aug 02 '22 at 02:24
  • @zuker, that's not surprising, because _piping_ to another command (`Tee-Object`, in this case) equally involves a capturing `psql`'s output via an IPC pipe. – mklement0 Aug 02 '22 at 02:31
  • i try " >a.log" or " 2>&1 > a.log",get the wrong answer "UTF-8". It seems like I can't write the correct result('gbk') to a variable or file – zuker Aug 02 '22 at 08:46
  • @zuker, all of these variations will predictably yield the same result as `$a=...`, because they all involve capturing the program's output via a pipe. What is the meaning of the value? Is it meant to reflect the encoding that the _database_ uses, or the encoding that the `psql` CLI itself uses for its output? – mklement0 Aug 02 '22 at 15:16

1 Answers1

1

Thank you very much for your comments

When I look at the postgres doc

I find notty or tty will lead 'ttl' to different values

I can set 'PG CLIENT ENCODING' to solve the problem

zuker
  • 21
  • 3