Business Problem/Scenario

I had a .bat file with 50 lines or more, and many of them had disk paths. We were migrating this to production, so I did “replace all” commands to change all the paths to production SAN/Server names. But then, I knew some of the paths existed, and some didn’t. So I wanted to find all the paths that didn’t exist, so either:
1) I could fix the filename, or
2) Create the path on the disk

So I needed to parse the file looking for file/path names. At first I tried RegEx, but then decided that just using “Split” was faster in my case. (Sometimes you just want to get the job done in the shortest amount of time.)

The following works when you have a prefix on each directory path. I’m sure there are variations you could make on this depending on your filenames. I’m only looking for lines that have .exe, because the .bat file is running various C# program to process the files.

Sample file Test.bat:

line1 Small.exe \\MyServer\Messages\Dir1 and more words
line2 Biggertest2.exe \\MyServer\Messages\Dir1 parm2 \\MyServer\Messages\Dir2 parm4

Sample Powershell Code:

$filename = "c:\Users\MyName\Documents\Powershell\Test.bat"
$linesOfFile = Get-Content $filename 
$pathPrefix = "\\MyServer" 
cls
foreach ($line in $linesOfFile) 
  {
     #Write-Host $line 
     if ($line.Contains(".exe")) 
       {
          #Write-Host 
          #Write-Host $line

          $tokens = $line -split " "
          foreach ($token in $tokens) 
            {
                if ($token.Contains($pathPrefix)) 
                    {
                       #Write-Host $token 
                       if (-Not (Test-Path $token))
                          {
                             Write-Host "Not Found: $token "
                          }
                       else 
                          {
                             #Write-Host "Found: $token "
                          }

                    }
            }

       }
  }

Results (Output):

Not Found: \\MyServer\Messages\Dir1
Not Found: \\MyServer\Messages\Dir1
Not Found: \\MyServer\Messages\Dir2

Subsequent Improvements:

Make the whole line upper case. Ignore lines that start with “REM” (remarks/comments).
Future enhancement, could also make sure that the .exe files exist.

     #before loop
     $pathPrefix = $pathPrefix.ToUpper() 

     #inside loop 
     $line = $line.ToUpper()  
     if ($line.Contains(".EXE") -and -not($line.StartsWith("REM"))) 

Filed under: Powershell