Wednesday, August 29, 2012

PowerShell : Code to FTP files from windows to unix server


Recently I had to write a script in windows to interact with Sql Server and FTP for one of the client requirements.

There I thought about using windows batch scripting, VBScripting but PowerShell turned out to be a complete solution for me.

I am just too amazed with the enormous features of PowerShell, It's ability to build and test code at the command prompt just like Unix.
Its best alternative for shell scripting geeks on windows platform.

A beginner may find Powershell bit complicated at the beginning but as you go on digging.... you will thrive to learn more and more.

henceforth I'll be sharing some useful powershell codes which I come across.

Here is the code I wrote to transfer files using ftp from windows to unix server.

# FTP FILES TO UNIX SERVER

foreach ( $FILE1 in $(get-childitem C:\Niraj\PowerShell\ps\abc) )
{
$ftpRemote = "ftp://UnixServerName/pathAfterUserHome/$FILE1"
$ftpLocal = $FILE1.FullName
$username = "NjUnixUsr"
$password = "pass1234"
$client = New-Object System.Net.WebClient
$credentials = New-Object System.Net.NetworkCredential -arg $username, $password
$client.Credentials = $credentials
$ErrorActionPreference = "silentlyContinue"
$client.UploadFile($ftpRemote, $ftpLocal)
if ($? -eq $false)
{  "$FILE1 transfer failed with error $error[0] " }
else
{  "$FILE1 ftp successful" }
}

OR


#below 3 lines creates an empty file with not even a single space or line in it.
"" > c:\nj\output\test123.txt
[array]$txt1 = Get-Content c:\nj\output\test123.txt
$txt1[1..($txt1.Count)] > c:\nj\output\test123.txt

#below 5 lines does the task of getting all filenames in test123.txt file on every line
$files2 = get-childitem c:\nj\images
foreach ( $FILE2 in $files2 )
{
"" + $FILE2 >> c:\nj\output\test123.txt
}

# Here process each file in for loop for ftp transfer
foreach ( $FILE1 in $(cat c:\nj\output\test123.txt) )
{
$ftpLocal = "C:\nj\images\$FILE1"
$username = "NjUnixUsr"
$password = "pass1234"
$client = New-Object System.Net.WebClient
$credentials = New-Object System.Net.NetworkCredential -arg $username, $password
$client.Credentials = $credentials
$ErrorActionPreference = "silentlyContinue"
$client.UploadFile($ftpRemote, $ftpLocal)

# Error check
if ($? -eq $false)
 {
  "$FILE1 transfer failed with error $error[0] "
 }
else
 {
  "$FILE1 ftp successful"
 }
}

1 comment: