Powershell and Unicode

by Lisa Dean

I’m writing a Powershell script that creates an FTP script and then runs the FTP command using that script. The file created fine and the FTP command ran but the FTP script did not work:
$exportDirectory = “\\server\share”
$file= “$exportDirectory\test.txt”

function FTP-File($FTPusername, $FTPpassword, $FTPfile){
      “open” > $exportDirectory\ftp.scr
      $FTPusername >> $exportDirectory\ftp.scr
      $FTPpassword >> $exportDirectory\ftp.scr
      “put $FTPfile” >> $exportDirectory\ftp.scr
      “quit” >> $exportDirectory\ftp.scr
      ftp.exe -s:$exportDirectory\ftp.scr

FTP-File “username” “password” $file

FTP error
After struggling with it for a few minutes I realized it might be a file encoding problem. That weird character on the first line seemed to point to that. I looked and the ftp.scr file was encoded as “UCS-2 Little Endian” — well that’s an odd format. Outside of the script I change the encoding of that file to ANSI and ran the FTP command and it worked perfectly.
So Powershell file redirection creates Unicode files and the command line does not understand Unicode. The fix? Use Out-File instead.
function FTP-File($FTPusername, $FTPpassword, $FTPfile){
      “open” | Out-File $exportDirectory\ftp.scr -Encoding ASCII
      $FTPusername | Out-File $exportDirectory\ftp.scr -Encoding ASCII -Append
      $FTPpassword | Out-File $exportDirectory\ftp.scr -Encoding ASCII -Append
      “put “ + $FTPfile | Out-File $exportDirectory\ftp.scr -Encoding ASCII -Append
      “quit” | Out-File $exportDirectory\ftp.scr -Encoding ASCII -Append
      ftp.exe -s:$exportDirectory\ftp.scr
      Remove-Item $exportDirectory\ftp.scr