0

I have a list of files on an FTP server that I am saving to a local drive. I'm also renaming the files based on their file extension. How can I save the files so that they overwrite any existing files but also rename in sequence, so if there are multiple files of the same extension they would be named ext.txt ext2.txt ext3.txt, etc? My code currently is overwriting files so that I end up with only 1 file per extension. Here's the relevant bit:

$myfiles | ForEach-Object{

$extension = ([System.IO.Path]::GetExtension($_.Name)).Trim(".")

$session.GetFiles($session.EscapeFileMask($remotePath + $_.Name), 
"$localPath\$extension.txt" ).Check()
}
Kyle
  • 403
  • 4
  • 15
  • You technically cannot rename a file and overwrite it. Either you rename the file in which case it is the same file with a different name. Or you save a new version of the file with the same name (overwrite). If you have a new version of the file that you want to save with a different name that will be two operations. Save the new file with the new name then delete the old file. As for how to sequence the names personally I would use a hash. Then for each extension you have an entry in the hash where the key is the extension and the value is the sequence number that you are on. – EBGreen Jul 18 '18 at 15:11
  • 1
    https://stackoverflow.com/q/45718716/ https://stackoverflow.com/q/18304025/ https://stackoverflow.com/q/39253435/ https://stackoverflow.com/q/18304025/ https://stackoverflow.com/q/1523043/ http://irisclasson.com/2013/12/14/renaming-files-in-a-folder-with-incrementing-number-in-powershell/ https://justanothersysadmin.wordpress.com/2008/03/22/bulk-rename-files-with-sequential-index/ – TessellatingHeckler Jul 18 '18 at 15:18

1 Answers1

1

TessellatingHeckler lists many near-duplicate question in his comment, but to address your specific scenario (focusing only on the sequence numbers, not the filesystem aspect):

$myFiles | ForEach-Object { $i = 0 } {

  $extension = ([System.IO.Path]::GetExtension($_.Name)).Trim(".")
  if (++$i -gt 1) {
    $extension += $i
  }

  # ...

}
  • Script block { $i = 0 } binds to the -Begin parameter of ForEach-Object, which is used for initialization before pipeline processing starts; in this case, the variable to hold the sequence number ($i) is initialized to 0.
    (You could rely on $i defaulting to 0 when you apply ++ for the first time later, but that would be brittle, as there may be a preexisting $i value.)

  • if (++$i -gt 1) { ... increments $i and only enters the block if its value is then greater than 1 (2 or greater).
    In effect, the block is only entered starting with the 2nd input object.

  • $extension += $i performs string concatenation (because $extension contains a [string] instance) and appends the sequence number to the extension, so that ext becomes ext2 when the block is first entered, for instance.

mklement0
  • 382,024
  • 64
  • 607
  • 775