Monday, November 16, 2015

Limiting recurse on Get-ChildItem in PowerShell 5

Sometimes when using Get-ChildItem, you want more than one but fewer than a near infinite number of results or you need it to take less than forever to return your results.

Let’s say you have a 10-terrabyte file share containing the home directories of thousands of users. You want to know who is storing .iso files and taking up lots of space unnecessarily.

If we use Get-ChildItem on the share, we aren’t going to get anything, because there are no files in the root path, only child folders. If we use Get-ChildItem with the -Recurse switch, it’s going to crawl through every subfolder of every subfolder of every subfolder… and it’s going to take three days, because someone let this share get way out of control, and Get-ChildItem is kind of slow.

We can, of course, write a simple script to scan a limited set of folders. But we’re scripters, and we’re lazy. Is there an easier way?

Starting in PowerShell 5, there is an easier way. They added a -Depth switch which simply tells it how far to recurse.

You can use a -Depth of 0, but that basically cancels out the -Recurse switch. You only get results from the root of your -Path.

001
Get-ChildItem \\FileServer1\HomeShare -Filter *.iso -Recurse -Depth 0


If you use a -Depth of 1, you search the root path, plus each of the folders in the root.

001
Get-ChildItem \\FileServer1\HomeShare -Filter *.iso -Recurse -Depth 1

With a -Depth of 2, you search the root path, each folder in the root, and each of their subfolders.

001
Get-ChildItem \\FileServer1\HomeShare -Filter *.iso -Recurse -Depth 2

In this hypothetical, I would just keep increasing the depth until I found a good balance point where I got as much good information as I could without taking too long to run.

No comments:

Post a Comment