Powershell sample program to write selected filenames (based on pattern) to a file (and/or console)

I needed a list of files from a huge directory of file for certain companies, and the company name was the prefix of the filename.

The company names are added to an array of strings.  This script recursively gets all filenames in a given directory, tests them to see if the start with any of the given prefixes, then writes to the console and to a given filename.

<pre>

$dir = "c:\Integrations\InvoiceOut\FTP\"
$outputFilename = "d:\scripts\selectedFiles.txt"

if (Test-Path $outputFilename)
  {
    #since we are appending to end of file, clean out the file on each run 
    #(or alternative put a date/time in the filename) 
    Remove-Item $outputFilename
  }

$prefixes = @()   #create new empty array 
$prefixes += "test1"
$prefixes += "test2"
$prefixes += "abc"
$prefixes += "def"
#put as many prefixes as you wish here... 

$files = get-childitem -path $dir -recurse -file
foreach ($file in $files)
  {
    $parts = $file.BaseName.Split("_")   #my files were in format prefix_date_other.txt
    if ($prefixes -contains $parts[0])
     {
       Write $file.Name #write to console
       Add-Content -Path $outputFilename $file.Name #write to file
     }
  }

</pre>

Note: You could also use $file.FullName to get the entire file name including the directory.
$file.BaseName is the file name without the directory and without the extension.
$file.Name is the file name without the directory (but with the extension).

If your filenames don’t have names like mine: CompanyName_text_text_text.txt, then you could do two loops.
One to loop through the prefixes and then to and use the C# string.StartsWith method to see if the file starts with that prefix. (Or instead of a prefix, maybe your search terms could be anywhere in the filename, use the C# string.IndexOf).

<pre>
#first part would be same as above 

$files = get-childitem -path $dir -recurse -file 
foreach ($file in $files) 
   {
       foreach ($prefix in $prefixes) 
         {
           if ($file.Name.StartsWith($prefix))   
           # or to search anywhere in filename: if ($file.Name.Indexof($prefix) -gt 0) 
              {
                 Write $file.Name  #write to console 
                 #Add-Content -Path $outputFilename $file.Name #write to file 
              }
          }
   }
</pre>

Uncategorized  

Leave a Reply