Tee utf-8 encoded

I am trying tee to output the server to both the console and the file in Powershell 4. The file ends with UTF-16 encoding, which is incompatible with some other tools that I use. According to help tee -full :

Tee-Object uses Unicode enocding when writing to files.
...
To specify the encoding, use the Out-File cmdlet

So, tee does not support changing the encoding, and the help for tee and Out-File does not contain examples of splitting a stream and encoding it using UTF-8.

Is there an easy way in Powershell 4 before tee (or split the stream otherwise) to a UTF-8 encoded file?

+6
source share
3 answers

One option is to use Add-Content or Set-Content instead of Out-File .

*-Content use ASCII encoding by default and have the -Passthru switch, so you can write to a file and then pass the input to the console:

 Get-Childitem -Name | Set-Content file.txt -Passthru 
+5
source

You will need to use -Variable , and then write it to a file in a separate step.

 $data = $null Get-Process | Tee-Object -Variable data $data | Out-File -Path $path -Encoding Utf8 

At first glance, it seems that it is easier to avoid tee altogether and simply capture the output in a variable, and then write it to the screen and to a file.

But because of how the pipeline works, this method allows a long pipeline to display data on the screen as it moves. Unfortunately, the same cannot be said for a file that will not be written until it is.

Doing both

An alternative is to flip your own tee so to speak:

 [String]::Empty | Out-File -Path $path # initialize the file since we're appending later Get-Process | ForEach-Object { $_ | Out-File $path -Append -Encoding Utf $_ } 

This will be written to the file and returned to the pipeline, and this will happen when it passes. This is probably pretty slow.

+2
source

First create a file using the appropriate flags, then add it:

 Set-Content out $null -Encoding Unicode ... cmd1 | tee out -Append ... cmdn | tee out -Append 
0
source

Source: https://habr.com/ru/post/988415/


All Articles