Wednesday 27 July 2011

Uploading all files from Directory to FTP from PowerShell Script

Issue:
     To Upload multiple files from Directory which matches the criteria like '.txt' '.exe' MIME Type.

Solution:
     To read all file from the Directory and uploading one by one. The code will be,
             #we specify the directory where all files that we want to upload are contained
             $Dir=<Path of the Directory>
             #ftp server
             $ftp = <FTP Path>
             $user = <UName>
             $pass = <Passwd>
             $webclient = New-Object System.Net.WebClient
             $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) 
             #list every sql server trace file
             foreach($item in (dir $Dir "*.txt"))
            {
                   "Uploading $item..."
                   $uri = New-Object System.Uri($ftp+$item.Name)
                   $webclient.UploadFile($uri, $item.FullName) 
            }


2 comments:

  1. I have created the similar script and added more functionlity, so sharing it here.

    http://msexchange.me/2014/03/05/upload-files-to-ftp-server/

    ReplyDelete
  2. hello,
    When i tried the above script, following is the error i am facing

    Uploading smaple1.txt...
    New-Object : Exception calling ".ctor" with "1" argument(s): "Invalid URI: The format of the URI could not be determined."
    At line:12 char:27
    + $uri = New-Object System.Uri($ftp+$item.Name)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

    Exception calling "UploadFile" with "2" argument(s): "Value cannot be null.
    Parameter name: address"
    At line:13 char:20
    + $webclient.UploadFile($uri, $item.FullName)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentNullException


    Please help in finding the solution

    ReplyDelete