我们想检查是否存在具有特定源名称的日志.日志创建如下:
New-EventLog -LogName Application -Source "MyName"
Run Code Online (Sandbox Code Playgroud)
现在我们要使用PowerShell函数来检查此日志是否存在.一个有效的解决方案如下:
[System.Diagnostics.EventLog]::SourceExists("MyName") -eq $false
Run Code Online (Sandbox Code Playgroud)
如果日志存在则返回False,如果不存在则返回true.
我们如何制作这段代码,以便它使用PowerShell的内置功能而不是.NET类?我们从这里尝试了代码:
$sourceExists = !(Get-EventLog -Log Application -Source "MyName")
Run Code Online (Sandbox Code Playgroud)
但它返回一个GetEventLogNoEntriesFound例外.
有人可以帮助我们吗?谢谢.
背景
我已经创建了一个包装器函数,Write-EventLog这样我就可以轻松地调用它,而不必每次都关心检查和创建事件日志/源.通过简单地添加一个-Force参数,我希望它创建日志,如果它不存在; 如果我不添加该参数,它应该正常运行(如果从我知道日志将存在的代码调用,这可以减少多次检查的开销).
我已经复制了可用参数列表,write-eventlog以便我可以使用包装器的全部功能.然而; 如果我不为这些参数中的某些参数提供值(例如RawData),则它们默认为null; 然后我最终尝试为此参数传递null; 这与不供应不同.我不想列出每个可能的参数组合迭代,并检查在调用适当的方法签名之前是否提供了这些值.
题
有没有办法只将值write-eventlog传递给传递这些参数的参数write-eventlog2?
码
cls
$myLog = 'Application'
$mySource = 'My PS Script'
$myEventId = 1
[System.Diagnostics.EventLogEntryType]$myEntryType = [System.Diagnostics.EventLogEntryType]::Error
$myMessage = 'This is a test message'
function Write-EventLog2
{
[cmdletbinding()]
param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[String]$LogName
,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[String]$Source
,
[Parameter(Position=3,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Int32]$EventId
,
[Parameter(Position=4,Mandatory=$false,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[System.Diagnostics.EventLogEntryType]$EntryType = [System.Diagnostics.EventLogEntryType]::Information
,
[Parameter(Position=5,Mandatory=$false,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[String]$Message
,
[Parameter(Position=6,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
[Int16]$Category = 1
,
[Parameter(Position=7,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
[String]$ComputerName = $env:COMPUTERNAME
,
[Parameter(Position=8,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
[Byte[]]$RawData
,
[Parameter(Position=9,Mandatory=$false,ValueFromPipeline=$false,ValueFromPipelineByPropertyName=$true)]
[switch]$Force
) …Run Code Online (Sandbox Code Playgroud)