Powershell变量/表达式的问题

时间:2015-04-02 07:47:31

标签: 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) } 
... Loop through LogEntries ...

1 个答案:

答案 0 :(得分:0)

错误讯息是什么? : - )

在最后一行代码中,您似乎错过了EventIDQueryAdd$EntryTypeQueryAdd的关键名称或两者之间的=符号(以及-colons)。

$LogEntries=Get-WinEvent -FilterHashtable @{logname="$ArgLogName"; $EventIDQueryAdd $EntryTypeQueryAdd StartTime=(Get-Date).AddMinutes(-$ArgLastMinutes) }

回想一下,哈希是键值对的集合。只是价值观没有意义。

一个选项,使用$EventIDQueryAdd(值为' EventIDQueryAdd')作为值为$EntryTypeQueryAdd的键(值为' EntryTypeQueryAdd') :

PS C:\>@{logname="$ArgLogName"; $EventIDQueryAdd=$EntryTypeQueryAdd; StartTime=(Get-Date).AddMinutes(-$ArgLastMinutes)}

@{logname="$ArgLogName"; $EventIDQueryAdd=$EntryTypeQueryAdd; StartTime=(Get-Date).AddMinutes(-$ArgLastMinutes)}

Name                           Value                                                                                        
----                           -----                                                                                        
logname                        LogName                                                                                      
StartTime                      2015-04-02 12:56:25 AM                                                                       
EventIDQueryAdd                EntryTypeQueryAdd  

使用不同键名的另一个选项:

PS C:\> @{logname="$ArgLogName"; SomeKey1=$EventIDQueryAdd; SomeKey2=$EntryTypeQueryAdd; StartTime=(Get-Date).AddMinutes(-$ArgLastMinutes)}

Name                           Value                                                                                        
----                           -----                                                                                        
SomeKey1                       EventIDQueryAdd                                                                              
logname                        LogName                                                                                      
StartTime                      2015-04-02 12:58:05 AM                                                                       
SomeKey2                       EntryTypeQueryAdd