4

Can someone give me a Powershell script that will change the format of all files in a folder from Unicode to ANSI? Here is a sample folder structure:

c:\DBObjects
  +StoredProcs
      - sp1.sql
      - sp2.sql
      - sp3.sql
  +Views
     - v1.sql
     - v2.sql
  .Functions
     - fn1.sql
     - fn2.sql

I tried the following script for one file and it worked. However it will create another file:

Get-Content sp1.sql -encoding Unicode | Set-Content sp1_Ansi.sql -encoding ASCII

Thank you!

rk1962
  • 1,713
  • 3
  • 24
  • 29

1 Answers1

10

Try

Set-Content sp1.sql -Encoding ASCII -Value (Get-Content sp1.sql)

Note that the entire file will be read into memory temporarily. If that's not acceptable, you'll need to use the pipeline method to write to a new file, then delete the old file, and rename the new file to the old file's name.

Josh
  • 68,005
  • 14
  • 144
  • 156
  • 1
    It worked! The following script forked for all files in one folder. `ls *.sql | forearch {sc $_ -encoding asciii -value(gc $_)}` . Can you tell me how to loop through all files in the subdirectories as well? Thank you! – rk1962 Jun 20 '12 at 12:39
  • 1
    I figured it out. `ls -re -include *.sql | forearch {sc $_ -encoding ascii -value(gc $_)} `. Please let me know if there is a better way of doing this. Thank you! – rk1962 Jun 20 '12 at 18:48
  • 1
    @rk1962, here is how I do it via files wild-cards (*.sql in this case): `Get-ChildItem *.sql | % { Get-Content $_ | Set-Content "$($_.basename)-ascii.sql" -encoding ASCII }` – Al Dass Aug 23 '15 at 17:18