powershellcarriage-returnlf

Powershell and .txt format


Cisco SX20 systems allow you to access their Web interface and download a backup of their configuration in a .txt file. I can open the file and manually change settings, then re-upload the file with no problems. Now, I have a Powershell script that will change certain settings within the backup file, then save it as a new .txt. When I try to upload this new file, I get an error:

"Invalid file uploaded."

I've checked to ensure my script isn't inadvertently changing any other information within the file and all the information is what it needs to be. The only difference is that the original backup file (downloaded from the Cisco Web interface) seems to use a UNIX (LF) format for readability, while the backup copy generated by Powershell uses the Windows (CR/LF) format. Is there any way my script is causing a compatibility issue with the Web interface?

$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} 

Solution

  • Out-File defaults to UTF-16 encoding. While the encoding shouldn't really matter, lots of applications out there cannot process UTF-16 because they assume that anything containing null bytes is random binary data and not text. You can add the -Encoding parameter to Out-File to specify an encoding to write the file in:

    Out-File ... -Encoding ASCII
    

    This works if you in fact have only ASCII data. If it's Unicode, then use -Encoding UTF8 instead. For things shared with other systems you should refrain from using -Encoding Default or -Encoding OEM which are both encodings specific to your system configuration. Do not expect them to work at all with other systems.