2

Unsuccessful with this code in appending the date to a flat text file when a pattern is matched in the file. Verified that the pattern is found and but not able to get the add-content to function. NOTE: the wait is used in order to wait until the keyword = Idle is written to the file.

my code is here:

$File = "AutoDE45oService_AP.$(get-date -Format yyMMdd).log"
        $Path = "C:\Users\user"
        $result = Get-ChildItem $Path -recurse | Where-Object { $_.Name -match $File } 
        $containsIdle = Get-Content $result.FullName -Tail 1 -Wait | Select-string -Pattern "Idle" -Quiet 
        If($containsIdle -contains $true)
{
    Add-Content $result.FullName -Value (Get-Date) -PassThru

    }
Configueroa
  • 315
  • 4
  • 14

2 Answers2

2

It doesn't make sense to combine Get-Content -Wait with Select-String -Quiet:

  • Get-Content -Wait waits indefinitely for new content being added to the target file, if any. Waiting only stops in exceptional circumstances, namely if the target file is deleted, renamed, or moved.

  • Select-String -Quiet only ever outputs one Boolean value indicating whether the pattern was found - even if additional input also contains that pattern.

Therefore, combining these two calls:

  • only ever produces at most one output value - namely $true - for the first occurrence of the pattern found - even if content added to the file later also matches the pattern.

  • keeps running indefinitely (unless you delete, rename or move the target file).


To solve your problem, you need two things:

  • Omit -Quiet and act on the results in a ForEach-Object that is part of the same pipeline:

    Get-Content -Wait ... | Select-String -Pattern ... | ForEach-Object { ... }
    
  • Provide an external mechanism that terminates the command to keep it from running indefinitely:

    • When running interactively, pressing Ctrl-C terminates execution.
    • For an automated, timeout-based termination mechanism, see this answer (to a related question of yours).
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Not entirely sure what part of your script you're trying to get into the log, but if you give something like this a shot, it might get better results than Add-Content.

Write-Output "The stuff you want in the log" | Out-File -FilePath $File -Append
Nick Schroeder
  • 1,340
  • 1
  • 13
  • 17