Skip to content

Instantly share code, notes, and snippets.

@alantsai
Last active September 18, 2019 13:56
Show Gist options
  • Save alantsai/edc488d41fe6e4bd39b0 to your computer and use it in GitHub Desktop.
Save alantsai/edc488d41fe6e4bd39b0 to your computer and use it in GitHub Desktop.
Set All *.cs file to utf-8 encoded 設定所有目前資料夾的 *.cs檔案,重新寫入成為utf-8 encoding #powershell

設定所有目前資料夾的 *.cs檔案,重新寫入成為utf-8 encoding

使用情景

有些時候建立的檔案不知道為什麼不是utf-8檔案,而是建立成了ansi編碼。在中文作業系統看不出來,因為通常非unicode語系都會設定成中文。但是一放到非中文作業系統,就會變成亂碼,造成程式無法編譯。

因此這個script用來把所有*.cs檔案另存成為utf-8編碼

Powershell Script

# Powershell 2.0用,沒有-File flag
#$files = Get-ChildItem . -Recurse -Filter "*.cs" | ? {Test-Path $_.FullName -PathType Leaf}
$files = Get-ChildItem . -Recurse -Filter  "*.cs" -File

foreach($file in $files)
{
    $content = Get-Content $file.FullName
    $content | Out-File $file.FullName -Encoding utf8
}

Reference

參考這篇:http://www.powershelladmin.com/wiki/Convert_from_most_encodings_to_utf8_with_powershell

# Powershell 2.0用,沒有-File flag
#$files = Get-ChildItem . -Recurse -Filter "*.cs" | ? {Test-Path $_.FullName -PathType Leaf}
$files = Get-ChildItem . -Recurse -Filter "*.cs" -File
foreach($file in $files)
{
$content = Get-Content $file.FullName
$content | Out-File $file.FullName -Encoding utf8
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment