Welcome!

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.

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.

 

   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: );
  15:  
  16: $script:CURRENT_DEPTH = 0;
  17:  
  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;
  29:   
  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:     }
  40:     
  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:     }
  49:  
  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:     }
  58:  
  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:   }
  74:   
  75:   $bIsMatch;
  76: }
  77:  
  78: #----------------------------------------------------------------
  79: # function Is-InDepthRange
  80: #----------------------------------------------------------------
  81: function Is-InDepthRange()
  82: {
  83:   param($context = $null);
  84:   
  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:   }
 103:   
 104:   $bInRange;
 105: }
 106:  
 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:   );
 117:   
 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:       }
 127:       
 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:   }
 141:   
 142: }
 143:  
 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:   );
 160:   
 161:   $context = @{
 162:     "maxdepth" = $maxdepth; "mindepth" = $mindepth;
 163:     "amin" = $amin; "atime" = $atime;
 164:     "empty" = $empty; "name" = $name; "path" = $path};
 165:  
 166:   Find-InDirectory -location $start -context $context;
 167: }
 168:  
 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
What is the best strategy for selecting the right offshore company for your business? In his session at 21st Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, will discuss the things to look for - positive and negative - in evaluating your options. He will also discuss how to maximize productivity with your offshore developers. Before you start your search, clearly understand your business needs and how that impacts software choices.
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
Enterprises are moving to the cloud faster than most of us in security expected. CIOs are going from 0 to 100 in cloud adoption and leaving security teams in the dust. Once cloud is part of an enterprise stack, it’s unclear who has responsibility for the protection of applications, services, and data. When cloud breaches occur, whether active compromise or a publicly accessible database, the blame must fall on both service providers and users. In his session at 21st Cloud Expo, Ben Johnson, C...
Most of the time there is a lot of work involved to move to the cloud, and most of that isn't really related to AWS or Azure or Google Cloud. Before we talk about public cloud vendors and DevOps tools, there are usually several technical and non-technical challenges that are connected to it and that every company needs to solve to move to the cloud. In his session at 21st Cloud Expo, Stefano Bellasio, CEO and founder of Cloud Academy Inc., will discuss what the tools, disciplines, and cultural...
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
21st International Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Me...
SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
With the rise of DevOps, containers are at the brink of becoming a pervasive technology in Enterprise IT to accelerate application delivery for the business. When it comes to adopting containers in the enterprise, security is the highest adoption barrier. Is your organization ready to address the security risks with containers for your DevOps environment? In his session at @DevOpsSummit at 21st Cloud Expo, Chris Van Tuin, Chief Technologist, NA West at Red Hat, will discuss: The top security r...
IBM helps FinTechs and financial services companies build and monetize cognitive-enabled financial services apps quickly and at scale. Hosted on IBM Bluemix, IBM’s platform builds in customer insights, regulatory compliance analytics and security to help reduce development time and testing. In his session at 21st Cloud Expo, Lennart Frantzell, a Developer Advocate with IBM, will discuss how these tools simplify the time-consuming tasks of selection, mapping and data integration, allowing devel...
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
Today traditional IT approaches leverage well-architected compute/networking domains to control what applications can access what data, and how. DevOps includes rapid application development/deployment leveraging concepts like containerization, third-party sourced applications and databases. Such applications need access to production data for its test and iteration cycles. Data Security? That sounds like a roadblock to DevOps vs. protecting the crown jewels to those in IT.
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Keisoku Research Consultant Co. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Keisoku Research Consultant, Co. offers research and consulting in a wide range of civil engineering-related fields from information construction to preservation of cultural properties. For more information, vi...