Powershell 变量/表达式的问题

Powershell 变量/表达式的问题

我正在尝试使用变量构建 Get-Winevent 命令,但我在“构建”命令中的变量方面遇到了问题,我遇到了众所周知的难题。在最后一部分代码中,如果我删除它,$EventIDQueryAdd命令$EntryTypeQueryAdd就会正常运行。任何帮助都将不胜感激!谢谢!

$ArgLastMinutes = 60
$ArgLogName = "Security"
$ArgEntryType = 0 
$ArgEventID = 4625
if ($ArgEventID) { $EventIDQueryAdd="id=$ArgEventID;" }
if ($ArgEntryType) { $EntryTypeQueryAdd="level=$ArgEntryType;" }

write-host "argeventid "$ArgEventID # returns 4625
write-host "argentrytype "$ArgEntryType # returns 1
write-host "eventidqueryadd "$EventIDQueryAdd # returns id=4625; as it should
write-host "entrytypequeryadd "$EntryTypeQueryAdd # returns level=1; as it should
$LogEntries=Get-WinEvent -FilterHashtable @{logname="$ArgLogName"; $EventIDQueryAdd $EntryTypeQueryAdd StartTime=(Get-Date).AddMinutes(-$ArgLastMinutes) }

... <循环遍历日志条目> ...

答案1

您尝试构建一个像字符串一样的哈希表,但这种方式行不通。当您说它returns id=4625; as it should不正确时,您得到的是字符串,而不是哈希表。对于哈希表,您应该看到以下输出:

Name    Value
----    -----
Id      4625

尝试这个:

$ArgLastMinutes = 60
$ArgLogName = 'Security'
$ArgEntryType = 0 
$ArgEventID = 4625

# Create a new hashtable with two keys
$Filter = @{
    LogName = $ArgLogName
    StartTime = (Get-Date).AddMinutes(-$ArgLastMinutes)
}

if($ArgEventID)
{
    # Add new key-value pair to the existing hashtable
    $Filter += @{Id = $ArgEventID}
}

if($ArgEntryType)
{
    # Add new key-value pair to the existing hashtable
    $Filter += @{Level = $ArgEntryType}
}

# Pass the hashtable to the -FilterHashtable parameter
$LogEntries = Get-WinEvent -FilterHashtable $Filter

相关内容