pawelemem
pawelemem

Reputation: 11

Script which choose latest file and sends it via FTP

I want this script to choose the latest file from a folder and then send it via ftp to the server.

I think it is choosing the file late because there is a new file on the FTP after running it. However it crashes constantly showing

uploading .....
uploading .....
uploading .....
$Dir="C:/log1"    
$ftp = "ftpftpftp" 
$user = "useruseruser" 
$pass = "passpasspass"  
$latest = Get-ChildItem -Path $Dir | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)  
 for($latest){ 
    "Uploading $latest..." 
    $uri = New-Object System.Uri($ftp+$latest.Name) 
    $webclient.UploadFile($uri, $latest.FullName) 
 } 

Upvotes: 0

Views: 125

Answers (1)

Matt
Matt

Reputation: 46730

I think you are using the wrong code block by accident. Currently you have created an infinite loop as you have no condition to how the for will exit.

A simple example of such a loop would be

for(){"Hello? Is it me you are looking for?"}

It should be structured like this

for (initialization; condition; repeat){code block}

an example would be

for($index =1; $index -lt 6;$index++){$index}

There is no need for that code block at all as long as $Dir is not empty. What you can do for a little error prevention is if($latest){} which will only work if $latest contains a file (in this code structure).

if($latest){ 
    "Uploading $latest..." 
    $uri = New-Object System.Uri($ftp+$latest.Name) 
    $webclient.UploadFile($uri, $latest.FullName) 
} 

Your sample output does not have a file name in it so I suspect your $dir contains no files?

Upvotes: 3

Related Questions