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; }