Monday, October 8, 2012

Scripting FTP in Windows PowerShell

What was supposed to be a straighforward task took me more than an hour.

I out-file my commands to a text file:

"ftpUserName`r`nSecretPassword`r`nDIR`r`nQUIT" | out-file ftpCommands.txt

And then:

ftp -i -s:ftpCommands.txt

But it did not work.  It says:

331 Password required for f.

and after a while:

User cannot log in.
Login failed.

It turns out that the default encoding for Out-File is Unicode.  That added two bytes to the beginning of the file ftpCommands.txt.  Somehow, the -s option of ftp does not open the file in the Windows way but treated the file literally byte for byte.

By explictly adding -Encoding ASCII to the Out-File command solved the problem.