Having an AppleScript Move All Files of a Certain Type From Sub-Folders to Trash

Greetings, everyone. With my introductory post, I would like to ask for help with an AppleScript I've been slaving over for the past five hours or so. I have tried Terminal and Finder commands both, along with lots and lots of Googling, and I cannot seem to get this to work.
Specfically, I want a script to look into a folder and all of its sub-directories, locate all files with a certain extension (in this case, APP), and then send every one of those files to the trash. Originally, I planned to delete them directly with Terminal commands that required verification, but I couldn't get that to work, and I thought that this would be a more average user-friendly version, anyway.
I also wondered if there was any universal means of referring to a system drive without referring to it by its name, since (as you'll see in the script) the directory that these *.app files will be moved from is in the Users/Shared hierarchy. However, it's meant to be used on multiple computers, so naming the OS drive on one won't work for others. If no such wild card exists, is what I'm doing now (having the script placed in the root folder of the OS drive) acceptable?
As it is, when I run this script, it displays all the dialogs, but the APP files aren't moved. It doesn't error at all in the AppleScript editor, it just runs and then closes down. I don't know what I'm doing wrong.
Thank you in advance for any help you can provide.
=====
if button returned of (display dialog "Trash all of the APP files in your SuchAndSuch folder? (This script must be in the root directory of your system drive.)" buttons {"Yes, I'm ready", "No"} default button 2 cancel button 2 with title "SuchAndSuch Folder Prep" with icon caution) is "Yes, I'm ready" then
    set theFolder to ":Users:Shared:SuchAndSuch:" as alias
    tell application "Finder"
        set theFiles to every file of theFolder whose name extension is "app"
        move theFiles to trash
    end tell
end if
if button returned of (display dialog "The APP files have been trashed." buttons {"OK"} default button 1 with title "SuchAndSuch Folder Prep" with icon 1) is "OK" then
end if

Well, you've done more fiddling than that; you've moved everything inside the Finder tell block.  Why did you do that?  If you recall my point 2 above, it is difficult to use POSIX paths or the POSIX file command inside Finder tell blocks without generating errors, but you've done both in your revision.  I'm surprised that you're surprised that it doesn't work. 
Applescript tries to be user-friendly, but it's still a programming language, and like any programming language the devil is in the details.  Changes that seem small and innocuous to you can make big differences in the result you get.
Now:
/Users/Shared should be machine independent in POSIX: you don't need to specify the hard drive name and it should be universal on all OS X installations.  You can specify it directly.
The Finder's delete command moves fils to the trash, it doesn't erase them.  Trying to use the move command to get files to the trash is a little bass-ackwards.
Don't put anything inside a Finder tell block unless it has to be processed by the Finder.  If you do you're just begging for errors.
There's no need to put the script at the root level of the drive.  If the Finder needs permission to delete a file it will ask.
untangled and revised:
set subfolderOfSharedFolder to quoted form of "/Users/Shared/<subfolder name>"
set response to display dialog "Trash all of the APP files in your <subfolder name> folder?" buttons {"Yes, I'm ready", "No"} default button 2 cancel button 2 with title "<subfolder name> Folder Prep" with icon caution
if button returned of response is "Yes, I'm ready" then
  -- run spotlight search
          set filesToDelete to paragraphs of (do shell script "mdfind 'kMDItemFSName == *.app c' -onlyin " & subfolderOfSharedFolder)
  -- convert posix paths to file specifiers
          repeat with thisFile in filesToDelete
                    set (contents of thisFile) to POSIX file thisFile
          end repeat
          tell application "Finder"
  delete filesToDelete
          end tell
          if button returned of (display dialog "The APP files have been trashed." buttons {"OK"} default button 1 with title "SuchAndSuch Folder Prep" with icon 1) is "OK" then
          end if
end if

Similar Messages

  • How to move all files but X to Y

    It doesn't really matter if it's in the terminal or if it's a applescript but I need to know how to:
    Move all files in a dictionary but a few named.

    Could you pleas explain more?
    If you do not understand the shell while loop, it is possible that using shell commands is a bit more dangerous than you might want to try.
    The explanation:
    ls -a | grep -v "X" | while read file
    do
        mv "$file" "Y/"
    done
    ls -a will list all the files in the current working directory (including the invisible files that start with a leading period.  Thinking about this, maybe you do not want to include -a.  You could cd /path/to/the/desired/directory as a way to set your current working directory as the directory you wish to move things from
    cd "/path/of/the/from/directory"
    ls | grep -v "X" | while read file
    do
        mv "$file" "Y/"
    done
    The ls command's output is piped (the vertical bar | ) into the grep command (general regular expression parser).  The -v option tells grep to throw away any lines (filenames) that match the regular expression "X".  So if the regular expression X matches all the files you do not want to move, the filenames send to the next pipe will be the files you wish to move.
    The while loop will read the filenames grep has selected and invoke the mv (move) command for each file selected by grep and move them to the destination directory Y
    The bigest risk is that you will execute this in the wrong directory and move the files that you need somewhere else.  OR WORSE, if "Y" is NOT a directory, and you DO NOT put a trailing / the mv could move easy file to the destination file, deleting the previous file for each file moved, so effectively deleting every file in the directory except the last one.
    This is why I said if you do not understand what is going on with the shell commands, you could do damage to your system.
    ls could have the /path/of/the/from/directory instead of using the cd command.  The grep command could be replaced with egrep that allows using alternate matching strings:
    ls /path/of/the/from/directory | egrep -v "abc.txt|def.jpg|xyz.mp3|etc..." | while read file
    do
        mv "$file" "/path/to/the/destination/directory/"  # notice the trailing slash for safety
    done
    Good luck.  I hope you do not destroy your system

  • How do I move all files from an old PPC to a new Mac Mini?

    How do I move all files from an old PPC to a new Mac Mini?

    The new mini has a Firewire 800 port. Likely the PPC version only has Firewire 400.  The OP will need a converter cable which is why I was asking first about what hardware is available and how much is being copied.
    Probably go with using the external hard drive if you decide all you want are data files.
    If you want to migrate:
    Kappy: A Basic Guide for Migrating to Intel-Macs - http://discussions.apple.com/message/10257343
    Mac OS X 10.3, 10.4: Transferring data with Setup Assistant / Migration Assistant FAQ - http://support.apple.com/kb/HT1554
    Setting-up a new Mac from an old one or its Backups - http://web.me.com/pondini/AppleTips/Setup.html

  • How to move all files to the top level folder?

    I want to move all files within a particular folder -- and all files in all sub folders -- to the top level. i.e. I want to collapse the folder structure to just one folder. Assume that there are no files with the same name.
    *Method 1*
    My first thought was to use Find:
    1. Limit Find to the particular folder.
    2. Find all files in the folder with Size > 0.
    3. Switch to List view. All files are listed.
    4. Select all files and drag to the top folder
    5. Delete all sub folders manually.
    Problem: Pages files are not found, and maybe others aren't.
    This is a simple method and I'd like to stick with it.
    *QUES 1*
    What condition should I set within Find so that I can be guaranteed of finding all files?
    *Method 2*
    It was suggested in another thread that I use Terminal to move all files to the top level, but I couldn't get it to work. And there was a problem with files that consist of bundles.
    *QUES 2*
    What is the easiest way to consolidate all files within a folder to the top level -- assume no duplicate names -- and at the same time remove all sub folders?
    Message was edited by: Guy Burns

    Thanks for the suggestion of EasyFind.
    To find all files in a certain folder I typed in *[a-z 0-9] as a Boolean search (this thread won't let me post the exact characters required by EasyFind). That should cover every file I've ever named. EasyFind came back with "11719found/12316done".
    Any idea what the missing 500 files would be? I'm hoping they are files that I don't need to know about (invisible files, system files and so on).
    Message was edited by: Guy Burns

  • RH8 + WinXP - Move all files after a build to version control?

    I am working with about 300 topics that are built into WebHelp.  Must I move all files from the WebHelp root and sub-folders to our Subversion folders after I have done a build with RH?
    From Subversion, the Help files are added "en masse" to the application.
    Can I move only those files that I've changed, if I am only changing content but I am not adding new topic files or deleting files?

    The odds of you actually identifying every, and I mean every, changed file are very low. Do yourself a favor.
    Good luck,
    Leon

  • How to move all the standard and adhoc reports from cube to multi provider

    How to move all the standard and adhoc reports from the basic cube to multi provider?
    i created this multiprovider to do the maintenence on the basic cube. for example the infocube physical partition, line item dimension and compression.
    what we decided to do is move all the Standard and ad-hoc reports from the basic cube to the multiprovider. How to do it? and make a copy of the basic cube and do the maintenence on the cube. please help.
    Thanks in advance sdn experts!

    Hi Les,
    This sounds good and one thing we try to always keep in mind when undertaking such activities is to always minimise the impact to the user and make the process as transparent to them as possible. So lets say you have your multiprovider and copied queries up in Prod, these queries will still pick up the data from the base cube.
    Now you need to make a copy of the base cube for some changes to the cube model, I would suggest that you copy the cube and make your changes on the copied cube itself. Then 9depending on the changes done) you can load data from Original Cube to New Cube. When this is being done, make sure that you change your queries to add a restriction on 0INFORPOV by Original Cube.
    After the load to the new cube is complete you can run reports restricted to each cube to verify the numbers. Then change the 0INFOPROV restriction in the queries to point to the New Cube and disengage the old cube from the multiprovider.
    Hope this helps...

  • HT1727 I want to move all my music (purchased and loaded from CD) from one computer to a new one?  I can synch purchased from my iPod but not CD copies.

    I want to move all my music (purchased and loaded from CD) from one computer to a new one?  I can synch purchased from my iPod but not CD copies.

    This user tip should be helpful too. It refers to the iPhone, but it's equally valid for iPods as well…
    Syncing to a "New" Computer or replacing a "crashed" Hard Drive

  • How is it posible to get the File name, size and type from a File out the H

    How is it posible to get the File name, size and type from a File out the HttpServletRequest. I want to upload a File from a client and save it on a server with the client name. I want to conrole before saving the name, type and size of the file.How is it posible to get the File name, size and type from a File out the HttpServletRequest.
    form JSP
    <form name="form" method="post" action="procesuploading.jsp" ENCTYPE="multipart/form-data">
    File: <input type="file" name="filename"/
    Path: <input type="text" readonly="" name="path" value="c:"/
    Saveas: <input type="text" name="saveas"/>
    <input name="submit" type="submit" value="Upload" />
    </form>
    proces JSP
    <%@ page language="java" %>
    <%@ page import="java.util.*" %>
    <%@ page import="FileUploadBean" %>
    <jsp:useBean id="TheBean" scope="page" class="FileUploadBean" />
    <%
    TheBean.doUpload(request);
    %>
    BEAN
    import java.io.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletInputStream;
    public class FileUploadBean {
    public void doUpload(HttpServletRequest request) throws IOException
              String melding = "";
              String filename = request.getParameter("saveas");
              String path = request.getParameter("path");
              PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("test.java")));
              ServletInputStream in = request.getInputStream();
              int i = in.read();
              System.out.println("filename:"+filename);
              System.out.println("path:"+path);
              while (i != -1)
                   pw.print((char) i);
                   i = in.read();
              pw.close();
    }

    Thanks it works great.
    Here an excample from my code
    import org.apache.commons.fileupload.*;
    public class FileUploadBean extends Object implements java.io.Serializable{
    String foutmelding = "geen";
    String path;
    String filename;
    public boolean doUpload(HttpServletRequest request) throws IOException
         try
         // Create a new file upload handler
         FileUpload upload = new FileUpload();
         // Set upload parameters
         upload.setSizeMax(100000);
         upload.setSizeThreshold(100000000);
         upload.setRepositoryPath("/");
         // Parse the request
         List items = upload.parseRequest(request);
         // Process the uploaded fields
         Iterator iter = items.iterator();
         while (iter.hasNext())
         FileItem item = (FileItem) iter.next();
              if (item.isFormField())
                   String stringitem = item.getString();
         else
              String filename = "";
                   int temp = item.getName().lastIndexOf("\\");
                   filename = item.getName().substring(temp,item.getName().length());
                   File bestand = new File(path+filename);
                   if(item.getSize() > SizeMax && SizeMax != -1){foutmelding = "bestand is te groot.";return false;}
                   if(bestand.exists()){foutmelding ="bestand bestaat al";return false;}
                   FileOutputStream fOut = new FileOutputStream(bestand);     
                   BufferedOutputStream bOut = new BufferedOutputStream(fOut);
                   int bytesRead =0;
                   byte[] data = item.get();
                   bOut.write(data, 0 , data.length);     
                   bOut.close();
         catch(Exception e)
              System.out.println("er is een foutontstaan bij het opslaan de een bestand "+e);
              foutmelding = "Bestand opsturen is fout gegaan";
         return true;
         }

  • How to move all files from a folder for a user to a centralized folder on a core server

    Hello,
    I'm curious if there is a batch file that can be made to move the contents that are setup like this....
    I'm having to redo a TS cluster and I'd like to make a batch file script that can be executed that moves the contents of say 'jsmith's local desktop profile @ \\NGTTS1\users\jsmith to a centralized folder on our roaming desktop profile server that saves
    all of the files for the desktops @ \\NGTFS1\users\jsmith.
    The problem I have is no matter what I tell users to save there files to our Y drive that is a folder that is synced across all 6 of our TS servers, users still store files on there desktops, so as you can imagine if one day they are on one server, then
    next day they could be on another and there files aren't the same.... hence the reason why I want to move all there files to the centralized server so when I redo the profiles from scratch on the TS server in the farm they suck files from the core server and
    have all of the files they are used to having.... 
    Now I know I can do this with a MOVE command I've just never done one to this exact.
    Hopefully someone knows the command to move all the contents of one folder on one server to the folder on a different server. I've already got the bulk of the coding done of the .bat script I just don't know this move command:
    would it be this:
    move \\NGTTS1\users\jsmith *.* \\NGTFS1\users\jsmith
    any help would be appreciated, I'm sure this is a easy command to do!
    This is the coding I have so far....
    @echo off
    color 0A
    title Moving Local Profile folder to Centralized Profile Folder on Core Server.
    :start
    echo Welcome, %USERNAME%
    echo What would you like to do?
    echo.
    echo 1. Moving Local Profile folder to Centralized Profile Folder on Core Server
    echo. 
    echo 0. Quit
    echo.
    set /p choice="Enter your choice: "
    if "%choice%"=="1" goto Move-user-profiles
    echo.
    if "%choice%"=="0" exit
    echo Invalid choice: %choice%
    echo.
    pause
    cls
    goto start
    :Move-user-profiles
    echo.
    set /p profile="Enter user profile: "
    move "\\NGTTS1\users\%profile%" *.* "\\NGTFS1\users\%profile%"
    echo moving files from local profile folder to FS1 profile server, stand-by...
    echo.
    goto cancel-special 
    :cancel-special
    set /p cancel="Type cancel to stop action: "
    if not "%cancel%"=="cancel" exit
    cls
    echo Action is cancelled.
    echo.
    pause
    exit

    In Windows we would do this using Group Policy.  There is a Policy setting that csn move the Desktop folder to any server you want to move it to.  Once set it will automatically do this for you.
    You should post in the Group Policy forum to find out how we use Group Policy to manage users profiles in Windows.
    You cannot use a script to relocate a users Desktop folder.  The desktop is locked by the time the users logon script is finished running.  It the desktop and profile are already being managed by Group Policy then this can only be done with GP.
    There are also numerous issues associated with deployment and re-deployment that you need to address  Post your questions in the Winows Deployment forum to get assistance with deployment issues.
    Again - want you are asking is not generally possible because of how Windows is designed.  This would only likely work on a simple system or on a stand alone PC and then only under a very limited set of circumstances.
    Use GP folder redirection to do this.  For deployment use Deployment Forum and for TS specific issues post in the RDS forum. 
    All of  this needs to be considered correctly for TS users inn a TS Cluster environment. (TS Cluster?? - not sure what you mean by that.
    ¯\_(ツ)_/¯

  • How to move all files from a folder for a user to a centralized folder on a core server with a GP

    Hello,
    I was curious if someone know how to move all the files of a user "local" profile on a Terminal Server to that of a centralized server where the "local" profile of like the user desktop, favorites, setting, etc are stored in the event
    the local profile on the TS become corrupt it can pull from this server...
    The problem I have is no matter what I tell users to save there files to our Y drive that is a folder that is synced
    across all 6 of our TS servers, users still store files on there desktops, so as you can imagine if one day they are on one server, then next day they could be on another and there files aren't the same.... hence the reason why I want to move all there files
    to the centralized server so when I redo the profiles from scratch on the TS server in the farm they suck files from the core server and have all of the files they are used to having.... 
    So I was curious and I've heard from some this is possible in a GP, but I'd like to move the contents of all 6 TS for
    each user or if I have to d this on  per user basis I will, just looking for a way to move the files....

    Hi Trevor,
    To move all users’ desktop to a server, we can use Folder Redirection to do this. The path for Folder Redirection is:
    [Group Policy Object Name]\User Configuration\Policies\Windows Settings\Folder Redirection
    In this situation, we can choose to redirect desktop to the root of a network file share or a folder on a network share.
    Regarding how to configure this, the following article can be referred to for more information.
    Configuring Folder Redirection
    http://technet.microsoft.com/library/cc786749.aspx
    Hope it helps.
    Best regards,
    Frank Shen

  • PSE 7 Move all files & folders to another location

    I have 3000 pictures in the following folder structure in Windows 7: C:\Users\User Name\Documents\My Pictures
    Under that structure there are 9 folders i.e., Family, Military Service, Friends etc. that contain the actual photos:
    I want to move the entire thing catalog and all to C:\My Photos
    without having to do a bunch of re-working.  There must be a way to do it but I can't figure it out.
    So that the 9 folders and all the sub-folders are directly under the C:\My Photos folder
    I cannot figure out how to do it.  The move command is constantly grayed out on my File Menu so I cannot access it.
    Thanks for any help
    John

    Hi Paige
    Well it does not seem to be working out for me.
    Here is what I am trying to accomplish.
    I just went to Windows 7.  I am using a dual boot system with two hard disk drives.  One has XP Pro on it which I used with PSE for years with no problems,  The other drive has Windows 7 on it. When I boot from the XP drive the Windows 7 drive becomes drive D and of course when I boot from the Windows 7 drive the XP drive becomes drive D.
    All of my PSE 7 photos on the XP drive are backed up to external drives using the PSE backup function.  I have PSE 7 installed on the Wlndows 7 drive and working.  The XP drive has the old file structure that I found to be laborious as I explained in my first post.  I wanted to import all of my pictures from one of the PSE backups onto the Windows 7 drive and use the new folder structure I described in my first post, C:\Family Photos.
    I booted using the Windows 7 drive, loaded PSE 7 and selected the backup recovery function.  I restored from the PSE backup drive which was Drive G  that was created by the backup function in the XP version of PSE 7.   I restored to a temporary folder (C:\Hold Pictures) using the original structure (C:\Documents and Settings\User Name\My Pictures.  My intent was to get the old file structure on to the Windows 7 drive and then using PSE folder display as you described move the pictures folder to C:\Family Pictures.  It restored the files correctly to the \Users\User Name\My Pictures folders of course it went much deeper than that to get to the actual pictures.  I then tried to move the folder (Pictures) using PSE but nothing worked right.  PSE seemed to handle it correctly but when I looked at the properties of the pictures in the catalog they were all to Drive D (the XP drive) using the old structure and not on the C: drive which they should have been..
    I finally gave up and will work on this again some other time.  I removed PSE7 from the Windows 7 computer in that it is probably a mess on the catalogs and I thought I had better start fresh.
    I hope all the above makes sense.  Obviously I am doing something quite wrong in the procedure
    Thanks for your help
    John

  • How do i find and move all files across multiple disks

    I just purchased a 2010 Mac Pro and wanted to set it up with a clean install of Mavericks.  I installed a new SSD as my boot disk and did a clean install of Mavericks on it.   All good so far.
    Now from my previous Macs I have several disks (internal and external) that have pictures, music and movies spread all over the place.
    I want to know how I can search all of the drives for all of a specific file type (i.e, JPEG or MP3) and then move those files to a new folder.  Once I have all of the files of a specific type in a single folder I can create a new library in iPhoto or iTunes using those files.
    I tried AraxisFDF and it worked well for finding the files but when it moves the files it saves then in their original file structure (i.e, volume/folder/folder/folder/file) which places the files in multiple folders again.
    Any ideas?
    Thanks.

    You can clone the respective HDDs using Disk Utility>Restore or Carbon Copy Cloner.  That will guarantee that you have all images and movies backed up.
    Ciao

  • How to move all files in Organizer to a network location

    I have a fairly large catalog with about 20 album categories, each with between 5 and 15 albums, totalling about 20,000 photos, all currently residing on my laptop. I need to move everything to a networked drive but can't find how in the Elements help system. Is there a quick and easy way to do this?
    Message title was edited by: Brett N

    If you have a complex folder structure, it may be best to do the backup/restore as this gives you the option of recreating the same folder structure at the destination location. If folder structure is no concern (that all files can just go to a single folder because you are using Albums instead), then the File > Copy/Move to Removable Drive command would be easiest. Just select the Move option and then choose your Network drive as the Destination Drive, use the Browse button to move the files to a specific folder on that drive.

  • I want to move all files to an external drive--how?

    I'm working on a Mac Pro. Using iMovie 9, I've been loading video from 10 years to archive and edit it all. I'm quickly using up remaining space on my primary hard drive (1 TB). I have a second drive (also 1 TB) with plenty of room. Can I move all the "Event" files (haven't started processing them yet) to this second drive? There doesn't seem to be any way to do this. Basically, I just want to move the whole iMovie operation to another drive and work from there. I've read some posts on this but the instructions don't make sense to me and I can't get anywhere.

    Here is the main post.
    https://discussions.apple.com/docs/DOC-4141
    The safest way is to follow the instructions in the post and move Events from within iMovie.
    In your case, if you have not started ANY projects, you can move the events in the Finder and they will still work.
    The safest way to do this would be to move a single Event using iMovie. This will create the right Events folder with the right name in the right place. Then drag the rest using the Finder. This will be a little quicker.
    Restart iMovie and it should see them all and you are good to go.
    Remember that the external drive must be formatted as MacOS Extended (journaled). FAT 32 drives would have to be reformatted before they can be used in iMovie.

  • Is it possible to select all files within a directory (and not the folders/subfolders)?

    For instance, in my iTunes directory, I would like to select all of the music files without selecting the other olders (artist name, album name). Going through with Shift+click and command+click will take an eternity. If I just highlight everything and hit "open", it will open ALL of the folders as well as opening the actual files. I want to skip the folders if possible with a mass selection.

    Well, its gonna be an expensive comparison since there is no non-arbitrary way to iterate through the files, but try:
    String f1, f2;  // the comparing files
    //get a primary list of files to iterate through
    Process p = Runtime.getRuntime.exec("ls");  // if in Linux
    BufferedReader pri =
        new BufferedReader(
        new InputStreamReader(
        p.getInputStream()));
    while((f1 = pri.readLine()) != null){    // for each file...
        Process q = Runtime.getRuntime.exec("ls");  // get all file names
        BufferedReader sec =
            new BufferedReader(
            new InputStreamReader(
            q.getInputStream()));
        while((f2 = sec.readLine()) != null){   // and for each of these
            if(!f1.equals(f2))  // as long as it's not the same file
                DO_COMPARISON(new File(f1), new File(f2));   // compare them
    }

Maybe you are looking for