I'm attempting to create a script that notifies me when a Windows application is down by monitoring a log file for specific keywords:
Get-Content <file> -Tail -Wait | Select-String -Pattern <keyword>
I also tried
Get-Content <file> -Tail -Wait | where {$_ -match <keyword>}
I can successfully retrieve the keyword that tells me the server is down using both variations of Get-Content
shown above. I know it's successful because I see the line of the keyword displayed on console. However, when I attempt to assign a variable:
$var = Get-Content <file> -Tail -Wait | Select-String -Pattern <keyword>
Write-Host $var
$var
It no longer displays the line containing the string on the console
Here's the actual script:
$Downstate = Get-Content -Path "C:\Program Files (x86)\logs\log1.txt" -Tail 1 -Wait |
Select-String -Pattern "tcp_disconnect"
Write-Host $Downstate
$Downstate
I also tried:
$Downstate = Get-Content -path "C:\Program Files (x86)\logs\log1.txt" -Tail 1 -Wait |
where {$_ -match "tcp_disconnect"}
I tried both Write-Host
and Write-Content
BTW.
I get no errors when I assign to a variable, I just can't see the output on the console. But if I don't assign to a variable, I can see the output.
Ultimately what I want is to assign a variable to an up and down condition so that I can reference to them in my script when I'm ready to create a logic that does something during given condition.
The following approach works for me:
$infile = 'D:\PShell\DataFiles\so_57360147.txt' ## my test case
$infile = 'C:\Program Files (x86)\logs\log1.txt'
Get-Content -path "$infile" -Tail 1 -Wait |
Select-String -pattern "tcp_disconnect" |
ForEach-Object {
$Downstate = $_
Write-Host $Downstate -Foreground Cyan ## debugging
$Downstate ## real output
}
Explanation derived from the Get-Content
docs Parameters:
Wait
Keeps the file open after all existing lines have been output. While waiting,
Get-Content
checks the file once each second and outputs new lines if present. You can interruptWait
by pressing CTRL+C. Waiting also ends if the file gets deleted, in which case a non-terminating error is reported.
Wait
is a dynamic parameter that the FileSystem provider adds to theGet-Content
cmdlet. This parameter works only in file system drives.Wait
cannot be combined withRaw
.