Follow sqlserver-dba.com

Subscribe to RSS feed  Follow @jackvamvas - Twitter

*Use the Comments section for questions

SQLServer-DBA.com Links

Dba_db2_button

dba-ninja.com

SQL Server DBA Jobs

How to specify encoding when creating Powershell text file using Out-file

02 October,2019 by Tom Collins

Question: I've deployed a Powershell script - which includes a process to  dump out a resultset to a csv file. I'm having an issue where the file is saved with encoding type Unicode - whereas I want the file to be saved as ANSI . This is a Powershell code snippet , using the Powershell cmdlet Out-File 

 

(some_input) | select * -ExcludeProperty RowError, RowState, HasErrors, Name, Table, ItemArray | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1| Out-File -filepath  myoutputfile.txt

When I  open the file in Notepad - and attempt a Save As - the encoding displays as Unicode .

Unicode

 

 

How can I force Powershell to encode as ANSI ?

 

Answer:   It's possible to force the Encoding type through extending  the  use of Powershell cmdlet out-file. There is a parameter called -Encoding . This is the adjusted Powershell code snippet you originally  posted . The adjusted code snippet includes the addition of the -Encoding parameter as part of Out-File. 

The input data is piped and a ConvertTo-Csv is executed , piped to a Select which skips the first row , and then piped to an Out-File , including the explicit Encoding  

 

(some_input) | select * -ExcludeProperty RowError, RowState, HasErrors, Name, Table, ItemArray | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1| Out-File -filepath -Encoding Ascii myoutputfile.txt

lf you execute your code again - and open in Notepad - you should now see ANSI as the Encoding type

Let me know if this works or any other methods you found to manage the Encoding type 

Read more on Powershell and csv management 

Export-CSV Powershell (SQL Server DBA)

How to write remove-item results to text with powershell out-file

Powershell write to Word document (SQL Server DBA)


Author: Tom Collins (http://www.sqlserver-dba.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on How to specify encoding when creating Powershell text file using Out-file


sqlserver-dba.com | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact|Copyright & Disclaimer