Monday, August 31, 2015

Powershell script to upload files recursively to FTP server

Uploading the files recursively here "D:\test" is source folder and destination is FTP server
$ftp_uri = "ftp://demo.azurewebsites.windows.net/"
$user = "domain\username"
$pass = "Password"
$path= "D;\test"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
 foreach($item in Get-ChildItem -recurse $path)
{
  $relpath =    [system.io.path]::GetFullPath($item.FullName).SubString([system.io.path]::GetFullPath($path).Length + 1)
        if ($item.Attributes -eq "Directory")
         {
            try
             {
                Write-Host Creating $item.Name
                $makeDirectory = [System.Net.WebRequest]::Create($ftp_uri+$relpath);
                $makeDirectory.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
                $makeDirectory.Method = [System.Net.WebRequestMethods+FTP]::MakeDirectory;
                $makeDirectory.GetResponse();
            }
            catch [Net.WebException]
             {
                Write-Host $item.Name Directory may be already exists.
            }
            continue;
        }
        "Uploading $item to :  $relpath"
        $uri = New-Object System.Uri($ftp_uri+$relpath)
        $webclient.UploadFile($uri, $item.FullName)
    }

0 comments:

Post a Comment