yanickaps
yanickaps

Reputation: 13

Script to Move files one at a time and rename

I have a requirement to move *.csv files from Europe to a server located in North America where a service is listening to process the files as they arrive.

The issue I am having is on occasion the listener on the server will pick up the file as it being dropped and will attempt to process it and fail.

What I have been advised to do is move the file as .txt then rename it immediately when it appears in the destination directory. This works fine but I now need to automate this process for many files.

Note the listener service will also stop if too many files are renamed at once.

In simple terms

For Each *.txt in Folder c:\Source
  Move from  C:\Source to \\ne-ifs-app\IN_FIELD_SERVICE\
  Rename \\ne-ifs-app\IN_FIELD_SERVICE\*.txt *.csv
Repeat for next File

Upvotes: 0

Views: 1568

Answers (2)

Roman Zhdanov
Roman Zhdanov

Reputation: 1

Thank you so much for the snippet.

I had a similar task, but needed to first rename the file, then move it, then change extension back to the original one.

Here is what I ended up with (I have never worked with PS code before and have limited knowledge of coding in general, so sorry for the sloppiness).

=====

$FirstPath = "C:\0001\"
$NewPath = "C:\0002\"
$Stuff = Get-ChildItem "$FirstPath\*.txt" | select name, fullname

ForEach($I in $Stuff){
  $curname = $I.name
  $modname = $curname -Replace "txt","csv"
  $CurFile = $FirstPath + $curname
  $newname = $FirstPath + $modname
  Rename-Item $CurFile $newname -Force
  Move-Item $newname $NewPath
  $NewFile = $NewPath + $modname
  $origname = $NewPath + $curname
  Rename-Item $NewFile $origname -Force
  Start-Sleep -s 1
}

=====

Upvotes: 0

Nate
Nate

Reputation: 862

If I understand what you're trying to do:

Set your variables of the current path, the new path and where you get your stuff:

$FirstPath = "C:\Source\"
$NewPath = "\\ne-ifs-app\IN_FIELD_SERVICE\"
$Stuff = Get-ChildItem "$FirstPath\*.txt" | select name, fullname

Now take each item from $Stuff and move it to your new path, rename the file at its new location, then wait 10 seconds to do it to the next file in $Stuff:

ForEach($I in $Stuff){
  $newfile = $NewPath + $I.name
  $newname = $newfile -Replace "txt","csv"
  Move-Item $I.fullname $NewPath
  Rename-Item $Newfile $newname -Force
  Start-Sleep -s 10
}

That should take care of that.

Upvotes: 2

Related Questions