簡體   English   中英

Powershell-編碼UTF8

[英]Powershell -Encoding UTF8

我有一個腳本,該腳本可以更改備份的.txt文件並保存一個新的.txt,可以用來上載到Cisco Web界面。 使用我的原始腳本,我將收到一個錯誤:

上傳的文件無效。

這是原始腳本:

$name = Read-Host 'What is the SX20 name?'
if ($name -notlike "SX20NAME[a-z , 0-9]*")
    {
        Read-Host 'Please begin naming conventions with "SX20NAME".'
        }
        else {
        $description = Read-Host 'What is the SX20 alias?'
        (Get-Content C:\Users\SX20_Backup.txt)|

Foreach-Object {$_-replace 'SX20NAME[a-z , 0-9]*' , $name}|
Foreach-Object {$_-replace 'SetAlias' , $description}|

Out-file $env:USERPROFILE\Desktop\$name.txt}

我在輸出文件中添加了-Encoding UTF8 ,因此現在看起來像這樣: Out-file $env:USERPROFILE\\Desktop\\$name.txt -Encoding UTF8} 因此,現在界面將接受該文件,但是我收到一條新的錯誤消息:

某些命令被拒絕:音量:“ 50”

“卷”恰好是備份文件中的第一行。 我可以調整些什么來解決此問題?

問題是它使用帶有BOM的 UTF-8,所以它 用零填充 在開頭添加一些額外的字符(最有可能是0xFFFE 如果您在十六進制編輯器中打開了文件,則可以看到它的作用。

之前我在Powershell中遇到過這個問題,不幸的是修復不是很好。 這個答案給出了正確的公式。

編輯 :更適合您的代碼,我認為這會工作。 注意我使用%別名代替ForEach-Object (它們是相同的)。

$name = Read-Host 'What is the SX20 name?'

if ($name -notlike "SX20NAME[a-z0-9]*") {
    Read-Host 'Please begin naming conventions with "SX20NAME".'
} else {
    $description = Read-Host 'What is the SX20 alias?'
    $newContent = (Get-Content C:\Users\SX20_Backup.txt) | %{ $_ -replace 'SX20NAME[a-z,0-9]*', $name } | %{$_ -replace 'SetAlias', $description}
    $filename = $env:USERPROFILE\Desktop\$name.txt
    [IO.File]::WriteAllLines($filename, $newContent)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM