【问题标题】:powershell search a certain line in a log file and create an event in event viewerpowershell 在日志文件中搜索特定行并在事件查看器中创建事件
【发布时间】:2019-08-07 15:13:13
【问题描述】:

我有问题;我想自动化一些东西:

我有一个 *.log 文件,其中包含记录的数据行; 我需要知道如何在 powershell 中创建一个脚本来搜索某一行,如果该行等于 0,则在 windows 事件查看器中创建一个事件。有人可以帮忙吗? 我的日志如下所示:

数据 = 1

测试 = 5

com = 5

连接数 = 1

当 *.log 文件中的 connection = 0 时,它应该在事件查看器中创建一个事件。 如果可能作为次要任务,我想每天运行两次这个脚本; 15:00 和 00 点。

谢谢!

试图用powershell找到= 0

Select-String -Path C:\Users\user\test.log -Pattern '= 0'
IF (Pattern '= 0')
{
Write-EventLog –LogName Application –Source “My Script” –EntryType 
Information –EventID 30000
}

收到错误:

Pattern : The term 'Pattern' is not recognized as the name of a cmdlet, 
function, script file, or operable program. Check the spelling of the 
name, or 
if a path was included, verify that the path is correct and try again.
At line:2 char:5
+ IF (Pattern '= 0')
+     ~~~~~~~
+ CategoryInfo          : ObjectNotFound: (Pattern:String) [], 
CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

【问题讨论】:

  • 我设法使脚本的第一部分工作,但现在,它不执行在 EventLog 中写入事件的第二部分:
  • PS C:\Windows\system32> $SEL = Select-String -Path C:\Users\user\test.log - 模式 "test =0" if ($SEL -ne $null) { Write-EventLog -LogName Eroare -Source scripts -Message “s-a gasit 0 in log” - EventId 15 -EntryType information } else { echo Not Contains String }
  • 上述方法有效,但会引发以下错误:Write-EventLog : 计算机“localhost”上不存在源名称“scripts”。在 line:5 char:5 + Write-EventLog -LogName Eroare -Source scripts -Message “s-a gasi ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [ Write-EventLog], InvalidOperationException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteEventLogCommand
  • PS C:\Windows\system32> New-EventLog -LogName Application -Source "scripts" 出现以下错误:Write-EventLog : The Log name "Eroare" does not exist in the computer"本地主机”。在 line:5 char:5 + Write-EventLog -LogName Eroare -Source scripts -Message “s-a gasi ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [ Write-EventLog], InvalidOperationException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteEventLogCommand

标签: powershell-4.0


【解决方案1】:

我设法解决了这个问题:):

确保您以管理员身份运行 Powershell,并且 您有权使用以下命令:

set-executionpolicy remotesigned 

在powershell中,然后:

$EVENT_SOURCE="verificare.ps1"

if ([System.Diagnostics.EventLog]::SourceExists($EVENT_SOURCE) -eq $false) {
   New-EventLog -LogName Application -Source ‘$EVENT_SOURCE’
   }

 $SEL = Select-String -Path C:\Users\user\test.log -Pattern "test =0"

if ($SEL -ne $null)
{
Write-EventLog -LogName Application -Source $EVENT_SOURCE -Message “found xxxxx in 
log” -EventId 30000 -EntryType information
}
else
{
echo Not Contains String
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    相关资源
    最近更新 更多