如何检查具有特定来源名称的事件日志是否存在?

How to check if event log with certain source name exists?

我们要检查是否存在具有特定来源名称的日志。日志创建如下:

New-EventLog -LogName Application -Source "MyName"

现在我们要使用 PowerShell 函数来检查此日志是否存在。一个可行的解决方案如下:

[System.Diagnostics.EventLog]::SourceExists("MyName") -eq $false

which returns 如果日志存在则为假,如果不存在则为真。

我们如何编写此代码以使其使用 PowerShell 的内置功能而不是 .NET 类?我们尝试了来自 here:

的代码
$sourceExists = !(Get-EventLog -Log Application -Source "MyName")

但它 returns 是一个 GetEventLogNoEntriesFound 异常。

有人可以帮助我们吗?谢谢。

您可以将其包装在 Cmdlet 中,如下所示:

function Test-EventLog {
    Param(
        [Parameter(Mandatory=$true)]
        [string] $LogName
    )

    [System.Diagnostics.EventLog]::SourceExists($LogName)
}

Note: You will need to run this script from an elevated PowerShell console (Run as Admin) for it to work:

Test-EventLog "Application"
True

正确的做法是,和上面差不多:

function Test-EventLogSource {
Param(
    [Parameter(Mandatory=$true)]
    [string] $SourceName
)

[System.Diagnostics.EventLog]::SourceExists($SourceName)
}

然后运行:

Test-EventLogSource "MyApp"

EventLog 和 EventLogSource 之间似乎有些混淆。

这是我的示例:(启用严格模式)

Set-StrictMode -Version 2.0

[System.String]$script:gMyEventLogSource = 'My Source'
[System.String]$script:gEventLogApplication = 'Application'



# custom event log sources
[bool]$script:gApplicationEventLogExists = [System.Diagnostics.EventLog]::Exists($script:gEventLogApplication)

if(!$script:gApplicationEventLogExists)
{
    throw [System.ArgumentOutOfRangeException] "Event Log does not exist '($script:gApplicationEventLogExists)'"
}

Write-Host "gApplicationEventLogExists ( $script:gApplicationEventLogExists )"

[bool]$script:gMyEventLogSourceExists = [System.Diagnostics.EventLog]::SourceExists($script:gMyEventLogSource)
Write-Host "gMyEventLogSourceExists ( $script:gMyEventLogSourceExists )"
if(!$script:gMyEventLogSourceExists)
{
    Write-Host "About to create event log source ( $script:gMyEventLogSource )" 
    New-EventLog -LogName $script:gEventLogApplication -Source $script:gMyEventLogSource
    Write-Host "Finished create event log source ( $script:gMyEventLogSource )"
    Write-Host ""
}