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

时间:2015-01-28 15:47:05

标签: powershell

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

New-EventLog -LogName Application -Source "MyName"

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

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

如果日志存在则返回False,如果不存在则返回true。

我们如何制作这段代码,以便它使用PowerShell的内置功能而不是.NET类?我们尝试了here的代码:

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

但它返回GetEventLogNoEntriesFound例外。

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

3 个答案:

答案 0 :(得分:2)

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

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

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

注意:您需要从提升的PowerShell控制台(以管理员身份运行)运行此脚本才能使其正常工作:

Test-EventLog "Application"
True

答案 1 :(得分:2)

正确的方法与上面几乎相同:

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

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

然后运行:

Test-EventLogSource "MyApp"

答案 2 :(得分:0)

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 ""
}
相关问题