Use PowerShell to Search for a Directory One Level Deep

This is a fairly simple on-liner. Assume you have a user home directories share wherein each user has a unique sub directory. There is a process that backs up to each users home directory when they upgrade to new computer. The backup directory is simply named backup. You need to find which users have lingering backup directories (perhaps they were never deleted).

A quick and easy way to generate a report, just run the following from the root of the share:

get-childitem | where {$_.PsIsContainer} | %{get-childitem $_ -filter backup | where {$_.PsIsContainer}} | select fullname | out-file c:\Results.txt

So, what are we doing?

  1. First, we use Get-ChildItem to give us all the items in the current directory. Note that gci, ls, and dir are aliases for Get-ChildItem and can be used interchangeably.
  2. We then pass that to a Where-Object and filter for objects that are containers, which means directories. Note that we could have used the ? alias to further shorten the command.
  3. We then pipe to a ForEach-Object loop. Within the loop, we do the following:
    1. Use Get-ChildItem with the filter parameter to retrieve all objects named “backup”. So, we’ve taken each directory in the root of the share and are now get the contents of them, thereby going one level deep into the directory structure.
    2. Use Where-Object to filter for only directories.
  4. We use Select-Object to return the fullname property of all the returned objects. Fullname includes the path.
  5. We then output to a text file with Out-File.

I’ve opted to do it all on the pipeline for several reasons. First and foremost, this is the sort of quick and dirty solution whose basic structure can be used to solve any number of problems on the fly. Second, if you have a large number of directories (or other objects if you modify this for something other than directory searches), it will be more memory efficient to pass each item down the pipeline as it becomes available than storing everything in variables in processing objects in bigger batches.

~Daniel

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s