PowerShell_unix PowerShell is definitely gaining momentum in the windows scripting world but I still hear folks wanting to rely on Unix based tools to get their job done.  In this series of posts I’m going to look at converting some of the more popular Unix based tools to PowerShell.

find

The Unix “find” command searches through one or more directory trees of a file system, locating files based on some user specific criteria.  By default, find returns all files below the current working directory.  It also allows you to perform an action to be taken on each matched file.

In my PowerShell script I have only included the “file location” functions and will leave adding the action feature as an exercise for the reader.

This script starts out by calling the Do-Find function which basically just stuffs all the command line arguments into a hash table and calls the function Find-InDirectory with the given start location.  Find-InDirectory will get all child items in the specified location and then iterate through that list.  If the child item is a directory, the current depth is incremented, a recursive call to the Find-InDirectory is made for the child directory, and then the current depth is decremented.  If the child item is a file, the Get-IsMatch function is called to determine whether the file matches the specified criteria from the command line arguments.

The Unix parameters map to the following in my PowerShell script:

Unix PowerShell Description
path -start The directory to start the search from (default = “.”).
-maxdepth -maxdepth Descend at most “n” levels of directories below start path.
-mindepth -mindepth Do not apply tests at levels less than “n” levels below start path.
-amin -amin Only process files that were accessed more recently than “n” minutes ago.
-atime -atime Only process files that were accessed “n”*24 hours ago.
-empty -empty Only process empty files or directories.
-name -name Only process files where file name matches “name” pattern.
-path -path Only process files where the full path matches the “path” pattern.
-exec -exec Execute expression on each match.  “{}” is replaced by file name in expr.