我有一些文本文件,其中包含有关Windows Scheduler作业的执行,我正在尝试从这些文件中读取特定值并发送电子邮件,
例如:File_1.txt
有以下几行,如果拒绝的计数大于0000000000
,我们应该得到通知。
RECORDS READ: 0000000042
RECORDS SKIPPED: 0000000000
RECORDS PROCESSED: 0000000042
RECORDS REJECTED: 0000000001
我尝试使用Get-Content
和Select-string
cmdlet来获取字符串“ Records Rejected: 0000000001
”,但不确定如何进行此操作。
$Output = Get-Content "C:\Powershell\Logs\*.log" |Select -Index 22
$output
$output = Select-String -Path 'C:\Powershell\Logs\*.log' -Pattern 'REJECTED:'
答案 0 :(得分:0)
这对文件的内容做出了很多假设,因此如果不起作用,则可能需要用更多详细信息更新问题:
$filename = "c:\src\scratch\text\log.txt";
# read an array containing each line of text from the file
# (there's a performance issue if the file has very many lines)
$lines = Get-Content -Path $filename;
# split each line into an array of words
# (another performance issue if the file is very large)
$records = $lines | % { @(, $_.Split(" ", [StringSplitOptions]::RemoveEmptyEntries)) };
# find the line where the second word is "REJECTED:"
# (assumes there's only ever exactly one "REJECTED" line)
# (arrays are zero-based so the first index is [0], and the second index is [1])
$rejected = $records | where-object { $_[1] -eq "REJECTED:" };
# convert the third word from that line into a number
$count = [int] $rejected[2];
write-host "rejected count = $count";
如果您觉得很勇敢,可以将其全部压缩到一个管道中,但是我将其扩展了,因此更容易看到正在发生的事情。
当我用您的示例文件运行它时,得到以下输出:
rejected count = 1
答案 1 :(得分:0)
这不是最漂亮的代码...实际上,它甚至都不是我不满意的代码...但是它可以工作,并且意图是它以您可以理解的方式工作!
旋转一下,看看你如何适应:-)
$file = "C:\temp\file.txt"
$content = Get-Content file
$rawRecordsRejected = $content | Where-Object {$_ -like "RECORDS REJECTED:*" }
Write-Host $rawRecordsRejected -ForegroundColor DarkYellow
$title = ($rawRecordsRejected -split ":")[0].Trim()
$recordsRejected = ($rawRecordsRejected -split ":")[1].Trim()
Write-Host $title -ForegroundColor Yellow
Write-Host $recordsRejected -ForegroundColor Green
答案 2 :(得分:0)
当左侧的对象是集合时,使用PoSh处理-match
的方式来获取拒绝计数。你得到的东西,不是布尔值。
# fake reading in a text file as raw text
# in real life, use Get-Content
$InStuff = @'
RECORDS READ: 0000000042
RECORDS SKIPPED: 0000000000
RECORDS PROCESSED: 0000000042
RECORDS REJECTED: 0000000001
'@ -split [System.Environment]::NewLine
$TargetLine = 'rejected'
$MaxRejectsAllowed = 0
$RejectedCount = [int]($InStuff -match $TargetLine).Split(':')[-1].Trim()
if ($RejectedCount -gt $MaxRejectsAllowed)
{
Write-Warning ('The Rejected_Records count [ {0} ] is above the threshold of [ {1} ].' -f $RejectedCount, $MaxRejectsAllowed)
}
输出...
WARNING: The Rejected_Records count [ 1 ] is above the threshold of [ 0 ].