如何确定EventLog是否已存在

Cha*_*ell 33 powershell eventlog-source event-log

我正在使用以下行创建一个新的事件日志

new-eventlog -LogName "Visual Studio Builds" -Source "Visual Studio"
Run Code Online (Sandbox Code Playgroud)

我想每次运行它,因为如果我从新计算机运行构建,我仍然希望看到事件日志.

问题是每次在创建日志后运行脚本时,都会抛出错误.

New-EventLog : The "Visual Studio" source is already registered on the "localhost" computer.
At E:\Projects\MyApp\bootstrap.ps1:14 char:13
+ new-eventlog <<<<  -LogName "Visual Studio Builds" -Source "Visual Studio"
    + CategoryInfo          : InvalidOperation: (:) [New-EventLog], InvalidOperationException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.NewEventLogCommand
Run Code Online (Sandbox Code Playgroud)

现在我知道我可以"搜索"事件日志

Get-EventLog -list | Where-Object {$_.logdisplayname -eq "Visual Studio Builds"} 
Run Code Online (Sandbox Code Playgroud)

但现在我如何确定它是否存在?

小智 41

# Check if Log exists
# Ref: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.exists(v=vs.110).aspx
[System.Diagnostics.EventLog]::Exists('Application');


# Ref: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.sourceexists(v=vs.110).aspx
# Check if Source exists
[System.Diagnostics.EventLog]::SourceExists("YourLogSource");
Run Code Online (Sandbox Code Playgroud)


Cha*_*ell 24

所以我正走在正确的道路上Get-EventLog.

我把它存储在变量中,而不仅仅是阅读它.然后我检查了变量是否null.

这已经实现了我的目标.

$logFileExists = Get-EventLog -list | Where-Object {$_.logdisplayname -eq "Visual Studio Builds"} 
if (! $logFileExists) {
    New-EventLog -LogName "Visual Studio Builds" -Source "Visual Studio"
}
Run Code Online (Sandbox Code Playgroud)

  • +1用于查找/共享问题的解决方案. (5认同)
  • 注意:仅在写入事件日志/来源时有效; 如果它已创建但未写入您将生成"已存在"异常. (4认同)

Sea*_*ebb 12

if ([System.Diagnostics.EventLog]::SourceExists("Visual Studio") -eq $False) { New-EventLog -LogName "Visual Studio Builds" -Source "Visual Studio" }

  • 我们希望答案有点冗长.教学如何钓鱼比仅用勺子喂养OP更好. (2认同)
  • 请注意,此脚本需要本地管理员权限才能工作.否则,无法访问某些事件日志(如securty),从而导致异常.两种情况都会抛出异常(true和false),因此无法通过捕获来确定日志是否存在. (2认同)

Sha*_*evy 11

检查Exists方法:

[System.Diagnostics.EventLog]::Exists('Visual Studio Builds')
Run Code Online (Sandbox Code Playgroud)