AutoHotKey: clean up OneDrive misery

Introduction

For some time now I use OneDrive on my computer. It always went very smoothly, let alone a number of smaller grieves, but last week it went wrong. Some time ago I deactivated the automatic update functionality because of other reasons. It did not occur to me that this could cause some troubles at a later stage. A couple of days ago I activated the automatic update functionality again. All of a sudden I noticed "double files".

This is what happened: OneDrive put back an older version of the file in the folder. The most recent version, actually the version I want to keep, was renamed with a suffix. The suffix is a hyphen followed by AEX199, which is the computer name. So in summary, I want to do 2 things:

  1. search for all files with suffix -AEX199
  2. check if in the same folder there is also a file with the same name, except for -AEX199
  3. delete the older file with the shorter name
  4. rename the newer file with the longer name without the suffix -AEX199

I immediately thought that the automation language AutoHotKey would be an ideal fit here. A few lines of code would suffice to clean up the files. PowerQuery would have been an option as well to import the file names to an Excel file, however we would still need VBA code. So that solution isn't better.

I now show you my code to clean up the files:

x := 0
folder := "D:\OneDrive"
Loop, files, %folder%\*-AEX199.*, R
{
    subfolder := A_LoopFileDir
    StringReplace, vPreviousFile, A_LoopFileName, -AEX199
    IfExist, %subfolder%\%vPreviousFile%
    {
        x++
        FileDelete, %subfolder%\%vPreviousFile%
        FileMove %A_LoopFileFullPath%, %subfolder%\%vPreviousFile%
    }
}
msgbox %x%

In the end it's not a lot of code. The code cleaned out almost 1,000 files in a couple of seconds.

Code discussion

I think that the code is relatively straightforward. I have a loop through folders within a chosen folder. Also the subfolders within the folders are looped through given the R in the Loop statement (R = Recursive). The filename pattern contains that -AEX199 and a bunch of wildcard characters. Next I retrieve the folder and I remove -AEX199 (more precisely, I replace it with an empty string). If the resulting file exists, I know I will have to delete a file and rename another file (in the correct sequence given file name conflicts). We can do that with FileDelete and FileMove, respectively. The variable x, finally, keeps track of how many cases the code encounters, and it is displayed in a message box at the end. Always useful to know.

Right, that's tidy again! Who knows you can use this code or you might have different useful appiclations in mind.




Homepage

Section contents

About Wim

Wim Gielis is a Business Intelligence consultant and Excel expert

Other links