PowerShell Script – How to Pull Files from PCs and FTP

ftpnetworkingpowershellscripting

I'm looking to write a script (preferably powershell) that will essentially copy a file from a bunch of PC's and FTP it to a server.

So the structure of the environment is that we have a file on multiple PC's (around 50 or so) that need to placed on a server. Sometimes one of the PC's may be turned off so the script would first need to ensure the PC is up and running (maybe a ping result), then it would need to go into a directory on that PC, pull a file off of it, rename the file, place into a source directory, then remove the file. Naming convention doesn't matter, but date/time stamp would be easiest. Ideally, it would be best to first move all the files to a source directory to save on FTP bandwidth, but since the files will be named the same, the files must be renamed during the move process. Move not copy because the directory needs to be empty so the file can be re-created the next day. So once moved to the source directory, now all the files need to be FTP'd to a server for processing.

After all of this, we need to know which PC's on the list did not respond so we can manually retrieve the file so the script should output a file (txt is fine) that will show which PC's were offline.

Everything is one domain and script will be run from an server with admin creds.

Thank you!

Best Answer

Edited :

$down = "C:\Script\log\down-hosts.log"
$nofile = "C:\Script\log\no-file.log"
$computers = Get-Content "C:\Script\list\Computers.txt"
$TargetPath = "\\server\directory\directory\"
$SourceFileName = "file_name.csv"
foreach ($computer in $computers) {
  if ( Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue 
{
    $sourcefilePath = "\\$computer\c$\UPS CSV Exports\$SourceFileName"
    Write-Host "$computer is up"
    Write-Host "Copying $SourceFilePath ..."
    Try {
      If (Test-Path $SourceFilePath) {
         Move-Item $SourceFilePath "$TargetPath\$computer`_$SourceFileName" -force
      } Else {
        #Throw "$SourceFilePath does not exist"
        Write-Host "$computer file does not exist"
        "$computer $SourceFileName file does not exist" | Out-File $nofile -append
      }
    } Catch {
       Write-Host "Error: $($Error[0].Exception.Message)"
    }
  } Else {
    Write-Host "$computer is down"
    "$computer is down $(get-date)" | Out-File $down -append 
  }
}

Some new explanations :

  • Use of Test-Connection to test if host is up (no ping). - Kept this as it worked well

  • Use of New-Item not necessary.

  • Use of Move-Item instead of FTP protocol.

  • Added new log features: "$computer $SourceFileName file does not exist" | Out-File $nofile -append which offers a second log showing the file did not exist.

  • Added new log feature: "$computer is down $(get-date)" | Out-File $down -append which shows the computer is down but also stamps it with a date/time.