none
Powershell Script to Copy an Unknown number of Files in a Directory RRS feed

  • Question

  • I need to be able to copy an unknown number of files in a folder to an FTP site.  I have the FTP components figured out and working, but am running into a problem when there is only 1 file for upload.  The folder is a queue that users manually copy files to, so i do not have control of how many files may be pending.  And the file names are always different.

    My script performs the following steps.

    1. Get a list of files in the directory with the a attribute.  (this prevents subfolders from being processed)

    2. Loop thru the list, copying each file.

    Here is my problem.

    • no files. nothing happens. normal and expected
    • 2 or more files. all files upload correctly.  EXPECTED
    • Filename returned from variable = "True".  File does not exist and upload fails.  ERROR

    This is what the script looks like. (There are several Write-Output statements for debugging purposes.

    $ftpUploadPath = "$ftpServer/claims/"
    $localUploadPath = "$localDir\claims\"
    $localSentPath = "$localUploadPath`Sent\"
    $listFile = "$localDir\uplist.txt"

    Write-Output "Uploading Claim files to $ftpUploadPath ..."

    #1 get list of claim files to upload
    $list = Get-ChildItem -Name $localUploadPath -Attributes a   
       
    Write-Output $list
    Write-Output " "
        
    #2 loop thru list and upload files
    if($list.Length -ne 0){
        #Write-Output "  Getting files from list"
        # download each file in the list
        foreach ($file in $list -cne "") {
            Write-Output $file

        } # end foreach file
    } #end if($list.Length)
    else {
        Write-Output "  No files for upload"
    } #end else($list.Length)

    Thanks in advance,

    Greg

    Monday, April 13, 2015 5:27 PM

Answers

  • You are writing way too many lines for such a simple task. Try this:

    Get-ChildItem -Name $localUploadPath -Attributes a   |
        ForEach-Object{
            Write-Host $_ -fore green
    $_ }


    \_(ツ)_/


    • Edited by jrv Monday, April 13, 2015 5:42 PM
    • Marked as answer by GDROBERTS_SMI Monday, April 13, 2015 6:44 PM
    Monday, April 13, 2015 5:41 PM

All replies

  • You are writing way too many lines for such a simple task. Try this:

    Get-ChildItem -Name $localUploadPath -Attributes a   |
        ForEach-Object{
            Write-Host $_ -fore green
    $_ }


    \_(ツ)_/


    • Edited by jrv Monday, April 13, 2015 5:42 PM
    • Marked as answer by GDROBERTS_SMI Monday, April 13, 2015 6:44 PM
    Monday, April 13, 2015 5:41 PM
  • Thanks, that worked.  I thought i may have been over-complicating it.
    Monday, April 13, 2015 6:45 PM
  • When a task becomes complicated it usually means you need to step back and ask the question in  anew or clearer way.

    Glad it helped.


    \_(ツ)_/

    Monday, April 13, 2015 10:21 PM