2016-05-31 111 views
0

我正在使用powershell創建文件,我需要此文件爲UTF8編碼,至此所有嘗試嘗試都失敗了。將Powershell創建的文件的編碼更改爲UTF8而不是UCS-2 LE

檢查記事本++中的文件顯示UCS-2 LE BOM作爲編碼。是否有可能爲powershell使用UTF8呢?

到目前爲止,我已經試過-encoding UTF8和我目前使用[IO.File]::WriteAllLines($filename, $text)

我收到此錯誤有可能是導致該問題的一個潛在的問題(請原諒我,給PowerShell的非常新)控制檯但文件被創建:

Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value. 
    + CategoryInfo   : InvalidArgument: (:) [Out-File], PSArgumentNullException 
    + FullyQualifiedErrorId : ArgumentNull,Microsoft.PowerShell.Commands.OutFileCommand 
    + PSComputerName  : 50.19.209.240 

ChangeFileModeByMask error (3): The system cannot find the path specified. 
    + CategoryInfo   : NotSpecified: (ChangeFileModeB...path specified.:String) [], RemoteException 
    + FullyQualifiedErrorId : NativeCommandError 
    + PSComputerName  : 50.19.209.240 

編輯:

給編輯提供更多信息的答案後。從文件

詳細說明:

write-host "Creating Application.conf in UTF-8" 
$filename = "c:\application.conf" 
[IO.File]::WriteAllLines($filename, $text, [System.Text.Encoding]::UTF8) 

在控制檯的輸出被示數仍然按照上面。

回答

1

您需要使用的WriteAllLines不同過載: File.WriteAllLines方法(字符串,字符串[],編碼),在這裏看到:https://msdn.microsoft.com/en-us/library/3det53xh(v=vs.110).aspx

這將是:

[IO.File]::WriteAllLines($filename, $text, [System.Text.Encoding]::UTF8) 

,當然還有您可以使用PS方式:

$text | Out-File $filename -encoding Utf8 
+0

嗨安德烈,我已經嘗試了這兩個建議,後者是我最初的嘗試,前者是我剛纔嘗試過的。我仍然收到控制檯中的錯誤,但它仍然以不希望的編碼創建它。你介意看看編輯過的帖子,看看是否有明顯的錯誤嗎? – null

+0

當然,段'$ text =「asdaasdad」 $ filename =「c:\ GAAAAAH.conf」 [IO.File] :: WriteAllLines($ filename,$ text,[System.Text.Encoding]: :UTF8)\t'本身工作正常。 – null

+0

它是在一個函數內,如果有幫助,它在文件內部調用。 – null

1

任何特殊原因,爲什麼使用.net類? 您也可以使用set-content cmdlet。

"text" | Set-Content -Encoding UTF8 -Path "c:\path\file.txt" 
+0

沒有理由,除了沒有真正知道任何不同。 :) – null

+0

那麼這種方法適合你嗎? – Martin

+0

目前沒有,我拿起這個腳本,並負責做一些改變。你可以看看編輯過的問題嗎? – null

相關問題