Wednesday, 9 September 2015

Powershell Find and Copy Files - Get-Childitem | Copy-Item


I have been playing around with PowerShell for some time now and I finally seem to be getting to grips with writing short but useful scripts. Apparently all I seem to do at work is prattle on about how "you could use PowerShell for that....." and so I thought perhaps I would share on the off-chance someone would be interested.

My son is taking Computer Science for his options and has been told that he is going to be learning PHP (which is kinda cool) and me being me, I happen to have some books on that topic ;-)

I am no Jeffrey Snover, Don Jones or Scripting Guy so don't expect anything fancy, there are plenty of people who know more than me, however, sharing is caring and all that jazz so here goes.

Whilst I have plenty of Electronic Books, I do however have one minor problem. All of the Electronic Books I have acquired over the last couple of decades are sitting on my NAS in a folder that contains 31.37GB of various PDF's/CHM's & other E-books. Being rather lazy and having no time to file them like a librarian, they are all either scattered about in the root of the drive or sitting in a few sub-folders. 

Needless to say, the built-in search facility in Windows using just *php*.* as the filter was a little bit crap and was taking an age. i had left it scanning for at least 1 hour while I got on with building DNS Server and only 30 or so books had been found out of an apparent 115. I became bored of watching windows fail to compile a "quick list" so I turned to my trusty friend PowerShell and wrote a script.

As I wanted a list of files that contained PHP in the title I used Get-Childitem with a filter for *php*.*

Get-ChildItem -Path '\\NASDrive\E-books' -File *php*.*

In order to provide the Full Path to Copy-Item as required, the following command:-

Select -ExpandProperty FullName

Provides the required result

\\NASDrive\E-books\Teach Yourself PHP, MySQL, And Apache In 24 Hours (2002).chm

This is then piped to the Copy-Item cmdlet with the required destination path. Here is the short but complete script.

Get-ChildItem -Path '\\NASDrive\E-books' -File *php*.* |
Select -ExpandProperty FullName |
Copy-Item -Destination "C:\UserPath\PHPBooks"

This way only took a minute or so and as expected the books appeared in all their glory. 115 Files/641MB all copied to my desktop in a very short time indeed.

Well, time to hang up the PowerShell apron and on to the next job.


Post a Comment