SYS-CON MEDIA Authors: Liz McMillan, Yeshim Deniz, Elizabeth White, William Schmarzo, Dana Gardner

Blog Feed Post

Unix To PowerShell - Find

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.


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.


   1: #----------------------------------------------------------------
   2: # Find.ps1
   3: #----------------------------------------------------------------
   4: param
   5: (
   6:   [string]$start = ".", # directory to start search in
   7:   [int]$maxdepth = -1, # decend at most "n" levels below starting line
   8:   [int]$mindepth = -1, # don't process levels less than mindepth
   9:   [int]$amin = -1, # file was last accessed "n" minutes ago
  10:   [int]$atime = -1, # file was last accessed "n"*24 hours ago
  11:   [bool]$empty = $false, # file is empty and is a file or directory.
  12:   [string]$name = "", # base of file name matches pattern.
  13:   [string]$path = "" # filename/path matches pattern.
  14: );
  16: $script:CURRENT_DEPTH = 0;
  18: #----------------------------------------------------------------
  19: # function Get-IsMatch
  20: #----------------------------------------------------------------
  21: function Get-IsMatch()
  22: {
  23:   param
  24:   (
  25:     $info = $null,
  26:     $context = $null
  27:   );
  28:   [bool]$bIsMatch = $true;
  30:   if ( Is-InDepthRange -context $context )
  31:   {
  32:     if ( $context["name"].Length -gt 0 )
  33:     {
  34:       $bIsMatch = $info.Name -like $context["name"];
  35:     }
  36:     elseif ( $context["path"].Length -gt 0 )
  37:     {
  38:       $bIsMatch = $info.FullName -like $context["path"];
  39:     }
  41:     if ( $bIsMatch -and ($context["amin"] -ne -1) )
  42:     {
  43:       $ts = [DateTime]::Now - $info.LastAccessTime;
  44:       if ( $ts.TotalMinutes -gt $context["amin"] )
  45:       {
  46:         $bIsMatch = $false;
  47:       }
  48:     }
  50:     if ( $bIsMatch -and ($context["atime"] -ne -1) )
  51:     {
  52:       $ts = [DateTime]::Now - $info.LastAccessTime;
  53:       if ( $ts.TotalHours -gt (24 * $context["atime"]) )
  54:       {
  55:         $bIsMatch = $false;
  56:       }
  57:     }
  59:     $bIsEmpty = $false;
  60:     if ( $info -is [System.IO.FileInfo] )
  61:     {
  62:       $bIsEmpty = $info.Length -eq 0;
  63:     }
  64:     elseif ( $info -is [System.IO.DirectoryInfo] )
  65:     {
  66:       $bIsEmpty = ( $info.GetFiles().Length -eq 0 );
  67:     }
  68:     if ( $context["empty"] ) { $bIsMatch = $bIsEmpty; }
  69:   }
  70:   else
  71:   {
  72:     $bIsMatch = $false;
  73:   }
  75:   $bIsMatch;
  76: }
  78: #----------------------------------------------------------------
  79: # function Is-InDepthRange
  80: #----------------------------------------------------------------
  81: function Is-InDepthRange()
  82: {
  83:   param($context = $null);
  85:   $bInRange = $true;
  86:   if ( $context )
  87:   {
  88:     if ( -1 -ne $context["mindepth"] )
  89:     {
  90:       if ( $script:CURRENT_DEPTH -lt $context["mindepth"] )
  91:       {
  92:         $bInRange = $false;
  93:       }
  94:     }
  95:     if ( -1 -ne $context["maxdepth"] )
  96:     {
  97:       if ( $script:CURRENT_DEPTH -gt $context["maxdepth"] )
  98:       {
  99:         $bInRange = $false;
 100:       }
 101:     }
 102:   }
 104:   $bInRange;
 105: }
 107: #----------------------------------------------------------------
 108: # function Find-InDirectory
 109: #----------------------------------------------------------------
 110: function Find-InDirectory()
 111: {
 112:   param
 113:   (
 114:     [string]$location = ".", # directory to start search in
 115:     $context = $null
 116:   );
 118:   $cis = Get-ChildItem -Path $location;
 119:   foreach ($ci in $cis)
 120:   {
 121:     if ( $ci.PSIsContainer )
 122:     {
 123:       if ( Get-IsMatch $ci -context $context )
 124:       {
 125:         $ci.FullName;
 126:       }
 128:       # Recurse through directories
 129:       $script:CURRdENT_DEPTH++;
 130:       Find-InDirectory -location $ci.FullName -context $context;
 131:       $script:CURRENT_DEPTH--;
 132:     }
 133:     else
 134:     {
 135:       if ( Get-IsMatch $ci -context $context )
 136:       {
 137:         $ci.FullName;
 138:       }
 139:     }
 140:   }
 142: }
 144: #----------------------------------------------------------------
 145: # function Do-Find
 146: #----------------------------------------------------------------
 147: function Do-Find()
 148: {
 149:   param
 150:   (
 151:     [string]$start = ".",
 152:     [int]$maxdepth = -1,
 153:     [int]$mindepth = -1,
 154:     [int]$amin = -1,
 155:     [int]$atime = -1,
 156:     [bool]$empty = $false,
 157:     [string]$name = "",
 158:     [string]$path = ""
 159:   );
 161:   $context = @{
 162:     "maxdepth" = $maxdepth; "mindepth" = $mindepth;
 163:     "amin" = $amin; "atime" = $atime;
 164:     "empty" = $empty; "name" = $name; "path" = $path};
 166:   Find-InDirectory -location $start -context $context;
 167: }
 169: Do-Find -start $start -maxdepth $maxdepth -mindepth $mindepth -amin $amin `
 170:   -atime $atime -empty $empty -name $name -path $path;

There are a few enhancements that could be made to this script such as better range checking to eliminate unnecessary directory recursion and also adding support for actions.

You can download the full source for the script here: Find.ps1

Read the original blog entry...

More Stories By Joe Pruitt

Joe Pruitt is a Principal Strategic Architect at F5 Networks working with Network and Software Architects to allow them to build network intelligence into their applications.

Latest Stories
Eric Taylor, a former hacker, reveals what he's learned about cybersecurity. Taylor's life as a hacker began when he was just 12 years old and playing video games at home. Russian hackers are notorious for their hacking skills, but one American says he hacked a Russian cyber gang at just 15 years old. The government eventually caught up with Taylor and he pleaded guilty to posting the personal information on the internet, among other charges. Eric Taylor, who went by the nickname Cosmo...
Most modern computer languages embed a lot of metadata in their application. We show how this goldmine of data from a runtime environment like production or staging can be used to increase profits. Adi conceptualized the Crosscode platform after spending over 25 years working for large enterprise companies like HP, Cisco, IBM, UHG and personally experiencing the challenges that prevent companies from quickly making changes to their technology, due to the complexity of their enterprise. An accomp...
The benefits of automated cloud deployments for speed, reliability and security are undeniable. The cornerstone of this approach, immutable deployment, promotes the idea of continuously rolling safe, stable images instead of trying to keep up with managing a fixed pool of virtual or physical machines. In this talk, we'll explore the immutable infrastructure pattern and how to use continuous deployment and continuous integration (CI/CD) process to build and manage server images for any platfo...
DevOpsSUMMIT at CloudEXPO, to be held June 25-26, 2019 at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Am...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
It cannot be overseen or regulated by any one administrator, like a government or bank. Currently, there is no government regulation on them which also means there is no government safeguards over them. Although many are looking at Bitcoin to put money into, it would be wise to proceed with caution. Regular central banks are watching it and deciding whether or not to make them illegal (Criminalize them) and therefore make them worthless and eliminate them as competition. ICOs (Initial Coin Offer...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
The current environment of Continuous Disruption requires companies to transform how they work and how they engineer their products. Transformations are notoriously hard to execute, yet many companies have succeeded. What can we learn from them? Can we produce a blueprint for a transformation? This presentation will cover several distinct approaches that companies take to achieve transformation. Each approach utilizes different levers and comes with its own advantages, tradeoffs, costs, risks, a...
Organize your corporate travel faster, at lower cost. Hotailors is a next-gen AI-powered travel platform. What is Hotailors? Hotailors is a platform for organising business travels that grants access to the best real-time offers from 2.000.000+ hotels and 700+ airlines in the whole world. Thanks to our solution you can plan, book & expense business trips in less than 5 minutes. Accordingly to your travel policy, budget limits and cashless for your employees. With our reporting, int...
This sixteen (16) hour course provides an introduction to DevOps, the cultural and professional movement that stresses communication, collaboration, integration and automation in order to improve the flow of work between software developers and IT operations professionals. Improved workflows will result in an improved ability to design, develop, deploy and operate software and services faster.
Enterprises are universally struggling to understand where the new tools and methodologies of DevOps fit into their organizations, and are universally making the same mistakes. These mistakes are not unavoidable, and in fact, avoiding them gifts an organization with sustained competitive advantage, just like it did for Japanese Manufacturing Post WWII.
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
There's no doubt that blockchain technology is a powerful tool for the enterprise, but bringing it mainstream has not been without challenges. As VP of Technology at 8base, Andrei is working to make developing a blockchain application accessible to anyone. With better tools, entrepreneurs and developers can work together to quickly and effectively launch applications that integrate smart contracts and blockchain technology. This will ultimately accelerate blockchain adoption on a global scale.
DXWorldEXPO LLC announced today that Nutanix has been named "Platinum Sponsor" of CloudEXPO | DevOpsSUMMIT | DXWorldEXPO New York, which will take place November 12-13, 2018 in New York City. Nutanix makes infrastructure invisible, elevating IT to focus on the applications and services that power their business. The Nutanix Enterprise Cloud Platform blends web-scale engineering and consumer-grade design to natively converge server, storage, virtualization and networking into a resilient, softwar...