I want to use a FileStream from the System.IO namespace instead of Get-Content cmd-let. How can I do that ?
thanks,
$fromaddress = "filemon@contoso.com"
$emailto = "IT@contoso.com"
$SMTPSERVER = "xx.xx.xx.xx"
$global:FileChanged = $false
$folder = "C:\temp"
$filter = "log.log"
$watcher = New-Object IO.FileSystemWatcher $folder,$filter -Property @{ IncludeSubdirectories = $false EnableRaisingEvents = $true }
Register-ObjectEvent $Watcher "Changed" -Action {$global:FileChanged = $true} > $null
while ($true)
{
while ($global:FileChanged -eq $false){
Start-Sleep -Milliseconds 100
}
if($(Get-Content -Tail 1 -Path $folder\$filter).Contains("Finished."))
{
Send-mailmessage -from $fromaddress -to $emailto -subject "Log changed" -smtpServer $SMTPSERVER -Encoding UTF8 -Priority High
}
# reset and go again
$global:FileChanged = $false
}
EDIT 1:
$fromaddress = "filemon@contoso.com"
$emailto = "IT@contoso.com"
$SMTPSERVER = "xx.xx.xx.xx"
$global:FileChanged = $false
$folder = "C:\tmp"
$filter = "log.log"
$watcher = New-Object IO.FileSystemWatcher $folder,$filter -Property @{ IncludeSubdirectories = $false ; EnableRaisingEvents = $true }
Register-ObjectEvent $Watcher "Changed" -Action {$global:FileChanged = $true} > $null
function Read-LastLine ([string]$Path) {
# construct a StreamReader object
$reader = [System.IO.StreamReader]::new($path)
$lastLine = ''
while($null -ne ($line = $reader.ReadLine())) {
$lastLine = $line
}
# clean-up the StreamReader
$reader.Dispose()
# return the last line of the file
$lastLine
}
while ($true)
{
while ($global:FileChanged -eq $false){
Start-Sleep -Milliseconds 100
}
$logFile = $Event.SourceEventArgs.FullPath
if ((Read-LastLine -Path $logFile) -match "Finished.")
{
write-host "mail sending"
Send-mailmessage -from $fromaddress -to $emailto -subject "Log changed" -smtpServer $SMTPSERVER -Encoding UTF8 -Priority High
}
# reset and go again
$global:FileChanged = $false
}
Message:
MethodInvocationException: C:\monfile.ps1:15
Line |
15 | $reader = [System.IO.StreamReader]::new($path)
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Exception calling ".ctor" with "1" argument(s): "The value cannot be an empty string. (Parameter 'path')"
InvalidOperation: C:\monfile.ps1:17
Line |
17 | while($null -ne ($line = $reader.ReadLine())) {
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
| You cannot call a method on a null-valued expression.
InvalidOperation: C:\monfile.ps1:22
Line |
22 | $reader.Dispose()
| ~~~~~~~~~~~~~~~~~
| You cannot call a method on a null-valued expression.