I've recently found myself using a software program that litters my project directory structures with "hidden" files. These all have a name like "._*" and they're used for the application to store its metadata in - even though I've repeatedly told it to NOT do that. It's annoying because I have to copy these files to customers, and they don't want to see all the stupid metadata folders, which don't stay hidden on the customers' file systems.
So I hacked out a quick PowerShell one-liner to delete them all.
This, I think, is a great illustration of how one-liners can get a job done without much scripting.
- I start by getting the directory from the current location (I have an H: drive mapped to it), and recursing subfolders.
- Where-Object only keeps those objects of the type DirectoryInfo. Keep in mind that Dir can also return FileInfo objects in the file system, so I'm basically discarding those.
- Whatever's left gets fed to ForEach-Object, which then retrieves the files from each folder. Looking at this now, I'm not sure why I didn't just elect to keep objects of the FileInfo type. Huh. Oh well, it works and I'm not changing it now. You can post your improved version in the comments :).
- Next, I keep only those files that match the naming criteria: ._* (* is a wildcard, obviously)
- For those files, I delete them. I think I could probably have called a Delete() method of the file, rather than calling the Del command and giving it the file's FullName property, but whatever. Gets the job done.
You know, the other point to make here is that when I "hack" something out, I really hack it out ;). I'm pretty careful when I'm teaching classes, but when I'm just trying to get stuff done on my own I'm happy for the result to be as ugly as it needs to be. Whatever gets the job done first, wins, and I rarely look back. There WAS a good reason why I got directories first and then got the files from each one, although for the life of me I can't remember that reason right now. I'll have to get back to you on that.