We are continuing our series that answers common questions, or questions that have been asked about/of PowerShell. Today our subject is Move Files to Unknown Directory. What we intend to provide is one of the many, many ways you can accomplish these same tasks within PowerShell.
All of the solutions are ours and demonstrate the author’s skill and ability level at the time of writing. That is to say, we might not always write the best PowerShell code, however, if you know of a better way we welcome that input.
The question is:
I have text files in C:\scripts\test. I want to move them into a new directory that is somewhere inside C:\scripts\plots\blob\ inside another directory. Is this possible with PowerShell?
The Answer:
Let’s review this. All text files are in C:\Scripts\Test
. You want to move the files from C:\Scripts\Test
to C:\scripts\plots\blob\infinitedirectorytree
.
Let’s assume that the directory we need to find and we are going to drop files into is named directoryWithData
.
With the ground rules (Review and Assuming) laid out it is time to begin. We need to use the $directoryWithData
variable we created and have it assist us. That way we can, the same command, recursively search C:\scripts\plots\blob\
. As that is where the directory named directoryWithData
resides. Then we pipe |
the information to Where-Object
to define the in-line variable $_
(Which is each directory per iteration) .PSIsContainer
and the text file. That would look like this:
Finally we need to now use the $directoryWithData
variable we created and have it assist us when moving files. To accomplish this we use Get-ChildItem
and point it to the location of the original text files. Then pipe | that information to Move-Item
with the -Destination
being the $directoryWithData.FullName
using dot(.
) notation to move the files into the correct directory without knowing where the directory actually resides.