0

I am trying to search for a string inside a file but it is simply not working in Powershell. I have tried many examples that are available at this link - https://java2blog.com/powershell-check-if-file-contains-string/ But none of them work. I have this IF statement inside of my file monitor (watching) script. So if a file is found, an action is created. But I want to try and identify a string inside the file so I can tell it where to go based on the string. But the "if ($result -ne $null) {" portion is always false. The file contains the 997 string but the script just doesn't find it. Any help would be greatly appreciated!

 #The Specified file contains the string
 $folder = 'C:\Some\File\Location\' # Enter the root path you want to monitor. 
 $filter = '*.*'  # You can enter a wildcard filter here.  

 # In the following line, you can change 'IncludeSubdirectories to $true if required.                           
 $fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property 
@{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 


 # Here, all three events are registerd.  You need only subscribe to events that you need: 

 $onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { 
    $name = $Event.SourceEventArgs.Name 
    $changeType = $Event.SourceEventArgs.ChangeType 
    $timeStamp = $Event.TimeGenerated 
    Write-Host "The file '$name' was $changeType at $timeStamp" -fore red 
    $changetype`: '$name'" 
    $path = $Event.SourceEventArgs.FullPath 

    $string = "997"
    $result = Select-String $path -Pattern $string -CaseSensitive
    if ($result -ne $null) {

       Write-Host "The specified text file contains the string '$string', Proceed to Copy, Move, & Send Email"



     $destination = 'C:\Some\NEW\File\Location\'
     $filedestination = 'C:\Some\NEW\File\Location\Workable%20Link\' 
     $copylocation = 'C:\Some\NEW\COPY\File\Location\' 
     $filepath = $filedestination+$name
     Copy-Item $path -Destination $copylocation -verbose
     Move-Item $path -Destination $destination -verbose


     # Function to create report email
     function SendNotification {
        $Msg = New-Object Net.Mail.MailMessage
        $Smtp = New-Object Net.Mail.SmtpClient($ExchangeServer)
        $Smtp.Port = 25
        $Smtp.EnableSsl = "true"
        $Smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $pass)
        $Msg.From = $FromAddress
        $Msg.To.Add($ToAddress)
        $Msg.Subject = "$reportname $dte"
        $Msg.Body = $EmailBody
        $Msg.IsBodyHTML = $true 
        $Smtp.Send($Msg)
     } 

    #Inside Loop Email
     $EmailBody = @"
      <html>
      <head>
     </head>
     <body>
      <p>The $reportname for <b>$partner</b> has been sorted.</p> 
      <p>You may view the file by clicking the link below</p>
      <p>$filepath</p>

      </body>
      </html>
      "@;

      SendNotification;

      Start-Sleep -Seconds 1;

      } else {
         Write-Host "The specified text file does not contain the string '$string'."
      }

   }

  while ($onCreated) { Start-Sleep -Milliseconds 1; }
Phil M
  • 67
  • 8
  • 1
    Not sure whether this is the cause of your issue (try to create a [mcve]) but [`$null` should be on the left side of the equality comparison](https://stackoverflow.com/q/58217913/1701026) – iRon Aug 08 '23 at 17:03
  • The only reason I included the rest of my script was due to the fact that it may have something to do with it. I am trying to run the IF statement inside of the Register-ObjectEvent when a file is shown as CREATED in the folder. So I wanted to demonstrate the scenerio. I am pulling the IF statements directly from the java2blog and have almost tried every one of them. The $path is correct I can actually Write-Host $path and it shows the correct path of the file before the IF statement. – Phil M Aug 08 '23 at 17:16
  • What kind of file are you searching? – Mathias R. Jessen Aug 08 '23 at 18:29
  • I think if $path and $string are valid that section should work fine - your error is further down. Add `Start-Transcript c:\path\to\your\logfile.log;` before `$name = $Event.SourceEventArgs.Name` - that will send your Write-Host commands and any errors to the filename you specify when the event fires. – MisterSmith Aug 08 '23 at 18:46
  • @Mathias I am searching a simple .txt file – Phil M Aug 08 '23 at 19:41
  • @MisterSmith - Sounds good! I will try that thank you! – Phil M Aug 08 '23 at 19:41

1 Answers1

0

Just following up on a solution. The Select-String wouldn't work with using a network location. So what I discovered is that it will work when looking inside the file if it is stored locally on the C:drive. In Theory, the example script I posted would have worked, because I didn't post the shared location of the file. Just make sure your file when using Select-String is opening a file on your local drive.

 $path = "//brd-share/my/shared/location/" (WILL NOT WORK)
 $path = "C:/My/File/Path/"  (Works!)
 Select-String $path
Phil M
  • 67
  • 8