PowerShell 技能连载 - 获取德国节日

这是一个PowerShell函数,可以获取所有德国的假日,无论是全国范围还是只针对你所在的州。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function Get-GermanHoliday
{
param
(
[int]
$Year = (Get-Date).Year,

[ValidateSet("BB","BE","BW","BY","HB","HE","HH","MV","NATIONAL",
"NI","NW","RP","SH","SL","SN","ST","TH")]
[string]
$State = 'NATIONAL'
)


$url = "https://feiertage-api.de/api/?jahr=$Year"

$holidays = Invoke-RestMethod -Uri $url -UseBasicParsing
$holidays.$State
}

运行上面的函数,然后直接运行原样的命令:

1
2
3
4
5
6
7
8
9
10
11
PS> Get-GermanHoliday

Neujahrstag : @{datum=2023-01-01; hinweis=}
Karfreitag : @{datum=2023-04-07; hinweis=}
Ostermontag : @{datum=2023-04-10; hinweis=}
Tag der Arbeit : @{datum=2023-05-01; hinweis=}
Christi Himmelfahrt : @{datum=2023-05-18; hinweis=}
Pfingstmontag : @{datum=2023-05-29; hinweis=}
Tag der Deutschen Einheit : @{datum=2023-10-03; hinweis=}
1. Weihnachtstag : @{datum=2023-12-25; hinweis=}
2. Weihnachtstag : @{datum=2023-12-26; hinweis=}

或者,提交额外的参数以获取给定州的特定假日:

1
PS> Get-GermanHoliday -State ni -Year 2023

假设您想知道德国节日 “Christi Himmelfahrt” 的日期。以下是获取该信息的方法:

1
2
3
4
5
6
7
8
9
# specify the name of the holiday to look up
$holidayName = 'Christi Himmelfahrt'

# get all holiday information
$holidays = Get-GermanHoliday
# get the particular holiday we are after, read the property "datum"
# and convert the string ISO format to a real DateTime:
$date = $holidays.$holidayName.datum -as [DateTime]
$date

PowerShell 技能连载 - 10个每个人都应该知道的有用PowerShell命令

许多开发人员喜爱PowerShell,而且理由充分:它增强了Windows命令提示符,在那里我们中的许多人花费大量时间。然而,它确实有一个学习曲线,但一旦掌握了基本指令,对你来说将是生产力的绝佳工具。

Cmdlets 是 PowerShell 功能能力背后的驱动力。开发人员应该知道数十个关键命令,这些命令涵盖从改进通用 Windows 体验到对开发工作有用的指令。此列表编制为刚开始使用者提供便于参考的工具。

Get-Help

对于任何使用 PowerShell 的人来说,Get-Help 命令至关重要,因为它提供即时访问所需信息以运行和操作所有可用命令。

以下是示例。

1
2
Get-Help [[-Name] <String>] [-Path <String>] [-Category <String[]>] [-Component <String[]>]
[-Functionality <String[]>] [-Role <String[]>] [-Examples] [<CommonParameters>]

Get-Command

Get-Command 是一个方便的参考 cmdlet,它显示当前会话中可访问的所有命令。

1
get-command

输出内容类似这样:

1
2
3
4
5
CommandType     Name                            Definition
----------- ---- ----------
Cmdlet Add-Content Add-Content [-Path] <String[...
Cmdlet Add-History Add-History [[-InputObject] ...
Cmdlet Add-Member Add-Member [-MemberType]

Set-ExecutionPolicy

为防止恶意脚本在PowerShell环境中运行,微软默认禁用了脚本。然而,开发人员希望能够构建和运行脚本,因此Set-ExecutionPolicy命令允许您调整PowerShell脚本的安全级别。您可以选择四种不同的安全级别:

Restricted: 这是默认的安全级别,阻止执行PowerShell脚本。在这个安全级别下只能交互式输入命令。

All Signed: 只有由可靠发布者签名的脚本才能运行在这个安全级别。

Remote Signed: 任何在本地生成的PowerShell脚本都可以在这个安全级别下运行。远程开发的脚本只有经过认可发布者签名后才被允许运行。

Unrestricted: 如其名称所示,无限制的安全级别从执行策略中移除所有限制,允许所有脚本运行。

Get-ExecutionPolicy

类似地,在陌生环境工作时,该命令可以快速显示当前执行策略:

Get-Service

了解系统上已安装哪些服务也是很有益处的。通过以下命令,您可以快速获取这些数据:

1
Get-Service

输出结果可能类似如下:

1
2
3
4
5
6
7
8
Status   Name               DisplayName
------ ---- -----------
Running AarSvc_4f948d3 Agent Activation Runtime_4f948d3
Running AdobeARMservice Adobe Acrobat Update Service
Stopped AJRouter AllJoyn Router Service
Stopped ALG Application Layer Gateway Service
Running AMD Crash Defen... AMD Crash Defender Service
Running AMD External Ev... AMD External Events Utility

如果您需要知道某个特定服务是否已安装,请在命令中添加“-Name”开关和服务的名称,Windows 将显示该服务的状态。还可以使用过滤功能返回当前安装的服务的指定子集。

Get-EventLog

PowerShell 中的 Get-EventLog 命令可真正解析计算机事件日志。有许多可用选项。要阅读特定日志,请使用“-Log”开关后跟日志文件名。例如,要查看应用程序日志,请执行以下命令:

1
Get-EventLog -Log "Application"

Get-Eventlog 的其他参数是:

  • -Verbose
  • -Debug
  • -ErrorAction
  • -ErrorVariable
  • -WarningAction
  • -WarningVariable
  • -OutBuffer
  • -OutVariable

Get-Process

通常很方便能够快速获得当前正在运行的所有进程的列表,就像获取可用服务列表一样。

这些信息可以通过 Get-Process 命令获得。

1
Get-Process

输出类似这样:

1
2
3
4
5
6
7
Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
206 13 2696 4320 0.38 13684 6 AdobeIPCBroker
110 8 2008 4224 3816 0 amdfendrsr
371 16 5996 12548 2528 0 AppHelperCap
502 29 20728 14560 1.64 9688 6 ApplicationFrameHost
124 8 1556 2204 5372 0 armsvc

Stop-Process

Stop-Process 可用于终止已冻结或不再响应的进程。如果不确定是什么导致了延迟,可以使用 Get-Process 快速发现问题进程。在获得名称或进程 ID 后,可以使用 Stop-Process 停止一个进程。以下是相同操作的示例:

1
Stop-Process -processname armsvc

Clear-History

如果您希望删除所有命令历史记录条目怎么办?使用 Clear-History cmdlet 很简单。它也可以用来仅删除特定的命令。例如,以下命令将删除以“help”开头或以“command”结尾的命令:

1
Clear-History -Command *help*, *command

ConvertTo-html

如果您需要提取数据以供报告或分发给他人,ConvertTo-HTML 是一种快速简便的方法。要使用它,请将另一个命令的输出传递给 ConvertTo-HTML 命令,并使用 -Property 开关指定您希望在 HTML 文件中包含哪些输出属性。您还需要为文件命名。

例如,以下代码创建了一个列出当前控制台中 PowerShell 命令的 HTML 页面:

1
get-commad | convertto-html > command.htm

结论

以下 cmdlet 是我在日常工作中经常使用的一些特别提及,也被许多 PowerShell 开发人员广泛使用。请在评论部分告诉我这篇文章中遗漏了什么,以便我们可以在接下来的文章中涵盖它。

PowerShell 技能连载 - 寻找开始时间退化

具有管理员权限的Windows系统可以访问在启动过程中收集到的诊断数据。Windows会记录每个服务和子系统的启动时间和降级时间(以毫秒为单位)。通过这些数据,您可以识别出需要花费过多时间来启动的服务可能存在的问题。

以下是一个脚本,它读取相应的日志文件条目并返回测量得到的启动时间:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#requires -RunAsAdmin

$Days = 180

$machineName = @{
Name = 'MachineName'
Expression = { $env:COMPUTERNAME }
}

$FileName = @{
Name = 'FileName';
Expression = { $_.properties[2].value }
}

$Name = @{
Name = 'Name';
Expression = { $_.properties[4].value }
}

$Version = @{
Name = 'Version'
Expression = { $_.properties[6].value }
}

$TotalTime = @{
Name = 'TotalTime'
Expression = { $_.properties[7].value }
}

$DegradationTime = @{
Name = 'DegradationTime'
Expression = { $_.properties[8].value }
}

Get-WinEvent -FilterHashtable @{
LogName='Microsoft-Windows-Diagnostics-Performance/Operational'
Id=101
StartTime = (Get-Date).AddDays(-$Days)
Level = 1,2
} |
Select-Object -Property $MachineName, TimeCreated,
$FileName, $Name, $Version,
$TotalTime, $DegradationTime, Message |
Out-GridView

PowerShell 技能连载 - Microsoft Graph PowerShell 社区示例页面

Microsoft Graph是一种新的统一编程模型,用于管理诸如 Microsoft 365 和 Azure 等云服务。许多基于旧云技术的 PowerShell 模块和命令已被弃用,并由 Microsoft Graph 命令替代。

为了帮助您快速找到基于 Microsoft Graph 的 PowerShell 解决方案来完成特定任务,社区在GitHub上建立了一个收集了 Microsoft Graph PowerShell 示例的页面,您可以在这里访问:https://github.com/orgs/msgraph/discussions/categories/samples

PowerShell 技能连载 - 管理文件共享

在您的网络上创建新的文件共享需要管理员权限以及以下 PowerShell 代码:

1
2
3
4
5
6
7
$Parameters = @{
Name = "Packages"
Path = "C:\Repo1"
FullAccess = "{0}\{1}" -f $env:userdomain, $env:username
}

New-SmbShare @Parameters

或使用经典参数:

1
PS> New-SmbShare -Name Packages -Path c:\repo1 -FullAccess 'domain\username'

只需确保以管理员权限运行此程序,并确保本地文件夹(在 -Path 中指定)确实存在。

PowerShell 技能连载 - 带有掩码的输入

为了安全地输入信息,脚本需要显示一个掩码输入。最简单的方法是使用 Read-Host -AsSecureString 命令:

1
2
# Read-Host
$entered = Read-Host -Prompt 'Enter secret info' -AsSecureString

或者,你可以使用一个带有 [SecureString] 类型参数的函数,并将该参数设置为强制性:

1
2
3
4
5
6
7
8
9
# mandatory parameter
function test([Parameter(Mandatory)][SecureString]$Secret)
{
"You entered secret: $Secret"
return $Secret
}

# run function with mandatory parameter
$entered = test

这样,您可以免费获得一个屏蔽的输入(在控制台窗口显示为“星号”,在ISE中显示为单独的输入框),但最终得到的是安全字符串,而不是明文。以下是一个简单的函数,可用于将安全字符串转换回纯文本:

1
2
3
4
5
6
7
8
9
filter Convert-SecureStringToString
{
param([Parameter(Mandatory,ValueFromPipeline)][SecureString]$SecureString)
[Runtime.InteropServices.Marshal]::
PtrToStringAuto(
[Runtime.InteropServices.Marshal]::
SecureStringToBSTR($SecureString)
)
}

现在您可以使用屏蔽输入来询问敏感用户信息,并在内部将其作为纯文本使用:

1
2
3
# Read-Host
$entered = Read-Host -Prompt 'Enter secret info' -AsSecureString |
Convert-SecureStringToString

PowerShell 技能连载 - 自动化控制面板

Windows 控制面板是系统配置的图形用户界面中心。你也可以通过控制台命令来启动控制面板:输入 control [ENTER]。然而,即使 PowerShell 也支持控制面板:

Get-ControlPanelItem 列出所有可用的控制面板项目,你可以通过名称或描述来搜索控制面板项目。以下命令可以找到与 “print” 相关的控制面板项目:

1
2
3
4
5
PS> Get-ControlPanelItem -Name *print*

Name CanonicalName Category Description
---- ------------- -------- -----------
Devices and Printers Microsoft.DevicesAndPrinters {Hardware and Sound} View and manage devices, printers, and print jobs

Show-ControlPanelItem 可以用来打开一个或多个控制面板项目。请注意,这些 cmdlet 不能自动化设置更改,但它们可以帮助快速识别和打开基于 GUI 的控制面板项目。与其花费多次点击来打开控制面板并找到适当的控制面板项目进行管理(比如本地打印机),您也可以使用 PowerShell 控制台并输入以下命令:

1
PS> Show-ControlPanelItem -Name *print*

注意:*-ControlPanelItem cmdlets 仅在 Windows PowerShell 中可用。

PowerShell 技能连载 - 轻松过渡至 Get-WinEvent

出于多种原因,你不应继续使用 Get-EventLog,我们之前已经解释了一些原因。在 PowerShell 7 中,Get-EventLog`` 已经被弃用。相反,应该使用 Get-WinEvent。它可以做到 Get-EventLog`` 能做的所有事情,而且更多。

不过,Get-WinEvent 使用起来可能有些麻烦,因为它需要使用类似哈希表或 XML 的结构来定义你所需的事件。因此,在下面,我们为你提供了一个相当冗长的代理函数,用于为 Get-WinEvent 添加向后兼容性。运行下面的代理函数后,你可以使用 Get-WinEvent 并传入与之前使用 Get-EventLog 时相同的参数。而且,你还会获得全新的 IntelliSense 功能,提示所有包含可能有趣信息的日志名称。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
function Get-WinEvent
{
[CmdletBinding(DefaultParameterSetName='GetLogSet', HelpUri='https://go.microsoft.com/fwlink/?LinkID=138336')]
param(

[Parameter(ParameterSetName='ListLogSet', Mandatory, Position=0)]
[AllowEmptyCollection()]
[string[]]
${ListLog},

[Parameter(ParameterSetName='LogNameGetEventlog', Mandatory, Position=0)] <#NEW#>
[Parameter(ParameterSetName='GetLogSet', Position=0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string[]]
[ArgumentCompleter({
# receive information about current state:
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)

# list all log files in the path
Get-WinEvent -ListLog * -ErrorAction Ignore |
Where-Object RecordCount -gt 0 |
Sort-Object -Property LogName |
# filter results by word to complete
Where-Object { $_.LogName -like "$wordToComplete*" } |
Foreach-Object {
# create completionresult items:
$completion = $_.LogName
if ($completion -like '* *')
{
$completion = "'$completion'"
}
$displayname = $_.LogName
$tooltip = '{0:n0} Records, {1:n0} MB' -f $_.RecordCount, ($_.MaximumSizeInBytes/1MB)
[System.Management.Automation.CompletionResult]::new($completion, $displayname, "ParameterValue", $tooltip)
}
})]
${LogName},

[Parameter(ParameterSetName='ListProviderSet', Mandatory, Position=0)]
[AllowEmptyCollection()]
[string[]]
${ListProvider},

<# Get-EventLog supports wildcards, Get-WinEvent does not. Needs to be corrected. #>
[Parameter(ParameterSetName='GetProviderSet', Mandatory, Position=0, ValueFromPipelineByPropertyName)]
[string[]]
${ProviderName},

[Parameter(ParameterSetName='FileSet', Mandatory, Position=0, ValueFromPipelineByPropertyName)]
[Alias('PSPath')]
[string[]]
${Path},

[Parameter(ParameterSetName='FileSet')]
[Parameter(ParameterSetName='GetProviderSet')]
[Parameter(ParameterSetName='GetLogSet')]
[Parameter(ParameterSetName='HashQuerySet')]
[Parameter(ParameterSetName='XmlQuerySet')]
[ValidateRange(1, 9223372036854775807)]
[long]
${MaxEvents},

<# NEW #>
[Parameter(ParameterSetName='LogNameGetEventlog')]
[ValidateRange(0, 2147483647)]
[int]
${Newest},

[Parameter(ParameterSetName='GetProviderSet')]
[Parameter(ParameterSetName='ListProviderSet')]
[Parameter(ParameterSetName='ListLogSet')]
[Parameter(ParameterSetName='GetLogSet')]
[Parameter(ParameterSetName='HashQuerySet')]
[Parameter(ParameterSetName='XmlQuerySet')]
[Parameter(ParameterSetName='LogNameGetEventlog')] <#NEW#>
[Alias('Cn')]
[ValidateNotNullOrEmpty()] <#CORRECTED#>
[string] <# used to be [String[]], Get-WinEvent accepts [string] only, should be changed to accept string arrays #>
${ComputerName},

[Parameter(ParameterSetName='GetProviderSet')]
[Parameter(ParameterSetName='ListProviderSet')]
[Parameter(ParameterSetName='ListLogSet')]
[Parameter(ParameterSetName='GetLogSet')]
[Parameter(ParameterSetName='HashQuerySet')]
[Parameter(ParameterSetName='XmlQuerySet')]
[Parameter(ParameterSetName='FileSet')]
[pscredential]
[System.Management.Automation.CredentialAttribute()]
${Credential},

[Parameter(ParameterSetName='FileSet')]
[Parameter(ParameterSetName='GetProviderSet')]
[Parameter(ParameterSetName='GetLogSet')]
[ValidateNotNull()]
[string]
${FilterXPath},

[Parameter(ParameterSetName='XmlQuerySet', Mandatory, Position=0)]
[xml]
${FilterXml},

[Parameter(ParameterSetName='HashQuerySet', Mandatory, Position=0)]
[hashtable[]]
${FilterHashtable},

[Parameter(ParameterSetName='GetProviderSet')]
[Parameter(ParameterSetName='ListLogSet')]
[Parameter(ParameterSetName='GetLogSet')]
[Parameter(ParameterSetName='HashQuerySet')]
[switch]
${Force},

[Parameter(ParameterSetName='GetLogSet')]
[Parameter(ParameterSetName='GetProviderSet')]
[Parameter(ParameterSetName='FileSet')]
[Parameter(ParameterSetName='HashQuerySet')]
[Parameter(ParameterSetName='XmlQuerySet')]
[switch]
${Oldest},

<# NEW #>
[Parameter(ParameterSetName='LogNameGetEventlog')]
[ValidateNotNullOrEmpty()]
[datetime]
${After},

<# NEW #>
[Parameter(ParameterSetName='LogNameGetEventlog')]
[ValidateNotNullOrEmpty()]
[datetime]
${Before},

<# NEW #>
[Parameter(ParameterSetName='LogNameGetEventlog')]
[ValidateNotNullOrEmpty()]
[string[]]
${UserName},

<# NEW #>
[Parameter(ParameterSetName='LogNameGetEventlog', Position=1)]
[ValidateRange(0, 9223372036854775807)]
[ValidateNotNullOrEmpty()]
[long[]]
${InstanceId},

<# NEW #>
[Parameter(ParameterSetName='LogNameGetEventlog')]
[ValidateNotNullOrEmpty()]
[ValidateRange(1, 2147483647)]
[int[]]
${Index},

<# NEW #>
[Parameter(ParameterSetName='LogNameGetEventlog')]
[Alias('ET','LevelDisplayName')]
[ValidateNotNullOrEmpty()]
[ValidateSet('Error','Information','FailureAudit','SuccessAudit','Warning')]
[string[]]
${EntryType},

<# NEW #>
[Parameter(ParameterSetName='LogNameGetEventlog')]
[Alias('ABO')]
[ValidateNotNullOrEmpty()]
[string[]]
[ArgumentCompleter({
# receive information about current state:
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)

if ($fakeBoundParameters.ContainsKey('LogName'))
{
$nofilter = $false
$chosenLog = $fakeBoundParameters['LogName']
}
else
{
$nofilter = $true
$chosenLog = ''
}
# list all log files in the path
Get-WinEvent -ListProvider * -ErrorAction Ignore |
Where-Object { $nofilter -or ($_.LogLinks.LogName -contains $chosenLog) } |
Select-Object -ExpandProperty Name |
Sort-Object |
# filter results by word to complete
Where-Object { $_ -like "$wordToComplete*" } |
Foreach-Object {
# create completionresult items:
$completion = $_
if ($completion -like '* *')
{
$completion = "'$completion'"
}
$displayname = $_
$tooltip = $_
[System.Management.Automation.CompletionResult]::new($completion, $displayname, "ParameterValue", $tooltip)
}
})]
${Source},

<# NEW #>
[Parameter(ParameterSetName='LogNameGetEventlog')]
[Alias('MSG')]
[ValidateNotNullOrEmpty()]
[string]
${Message},

<# NEW #>
[Parameter(ParameterSetName='LogNameGetEventlog')]
[switch]
${AsBaseObject},

[Parameter(ParameterSetName='ListGetEventlog')]
[switch]
${List},

[Parameter(ParameterSetName='ListGetEventlog')]
[switch]
${AsString}


)

begin
{
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Diagnostics\Get-WinEvent', [System.Management.Automation.CommandTypes]::Cmdlet)

# if the user chose the Get-EventLog compatible parameters,
# compose the appropriate filterhashtable:
$scriptCmd = if ($PSCmdlet.ParameterSetName -eq 'LogNameGetEventlog')
{
# mandatory parameter:
$filter = @{
LogName = $PSBoundParameters['Logname']
}
$null = $PSBoundParameters.Remove('LogName')

if ($PSBoundParameters.ContainsKey('Before'))
{
$filter['EndTime'] = $PSBoundParameters['Before']
$null = $PSBoundParameters.Remove('Before')
}
if ($PSBoundParameters.ContainsKey('After'))
{
$filter['StartTime'] = $PSBoundParameters['After']
$null = $PSBoundParameters.Remove('After')
}
if ($PSBoundParameters.ContainsKey('EntryType'))
{
# severity is translated to an integer array:

$levelFlags = [System.Collections.Generic.List[int]]@()

# string input converted to integer array:
if ($PSBoundParameters['EntryType'] -contains 'Error')
{
$levelFlags.Add(1) # critical
$levelFlags.Add(2) # error
}
if ($PSBoundParameters['EntryType'] -contains 'Warning')
{
$levelFlags.Add(3) # warning
}
if ($PSBoundParameters['EntryType'] -contains 'Information')
{
$levelFlags.Add(4) # informational
$levelFlags.Add(5) # verbose
}


# default to 0:
if ($levelFlags.Count -gt 0)
{
$filter['Level'] = [int[]]$levelFlags
}

# audit settings stored in Keywords key:
if ($PSBoundParameters['EntryType'] -contains 'FailureAudit')
{
$filter['Keywords'] += 0x10000000000000
}
if ($PSBoundParameters['EntryType'] -contains 'SuccessAudit')
{
$filter['Keywords'] += 0x20000000000000
}
$null = $PSBoundParameters.Remove('EntryType')
}
if ($PSBoundParameters.ContainsKey('InstanceId'))
{
$filter['ID'] = $PSBoundParameters['InstanceId']
$null = $PSBoundParameters.Remove('InstanceId')
}
if ($PSBoundParameters.ContainsKey('Source'))
{
$filter['ProviderName'] = $PSBoundParameters['Source']
$null = $PSBoundParameters.Remove('Source')
}

$PSBoundParameters['FilterHashtable'] = $filter
Write-Verbose ("FilterHashtable: " + ($filter | Out-String))

if ($PSBoundParameters.ContainsKey('Newest'))
{
$PSBoundParameters['MaxEvents'] = $PSBoundParameters['Newest']
$null = $PSBoundParameters.Remove('Newest')
}
}
$scriptCmd = if ($PSBoundParameters.ContainsKey('Message'))
{
$null = $PSBoundParameters.Remove('Message')
{ & $wrappedCmd @PSBoundParameters | Where-Object Message -like $Message }
}
else
{
{ & $wrappedCmd @PSBoundParameters }
}



$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}

process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}

end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#

.ForwardHelpTargetName Microsoft.PowerShell.Diagnostics\Get-WinEvent
.ForwardHelpCategory Cmdlet

#>

}

我们来做一个测试并尝试从系统日志文件中获取最新的 20 个错误。正如你很快看到的,Get-WinEvent 现在接受与 Get-EventLog 相同的参数。在查看结果时,你会迅速发现 Get-EventLog 没有正确返回事件日志消息,而 Get-WinEvent 则做到了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
PS> Get-EventLog -LogName System -EntryType Error -Newest 3

Index Time EntryType Source InstanceID Message
----- ---- --------- ------ ---------- -------
551873 Jun 02 06:40 Error DCOM 10010 The description for Event ID '10010' ...
551872 Jun 02 06:38 Error DCOM 10010 The description for Event ID '10010' ...
551848 Jun 02 03:35 Error DCOM 10010 The description for Event ID '10010' ...

PS> Get-WinEvent -LogName System -EntryType Error -Newest 3

ProviderName: Microsoft-Windows-DistributedCOM

TimeCreated Id LevelDisplayName Message
----------- -- ---------------- -------

02.06.2023 06:40:14 10010 Error The server {A463FCB9-6B1C-4E0D-A80B-A2CA7999E25D} did...
02.06.2023 06:38:14 10010 Error The server {A463FCB9-6B1C-4E0D-A80B-A2CA7999E25D} did...
02.06.2023 03:35:23 10010 Error The server {776DBC8D-7347-478C-8D71-791E12EF49D8} did...

请在参数中添加 -Verbose 选项,以获取关于过滤哈希表值或XML查询的详细信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
PS> Get-WinEvent -LogName System -EntryType Error -Newest 3 -Verbose
VERBOSE: FilterHashtable:
Name Value
---- -----
LogName {System}
Level {1, 2}

VERBOSE: Constructed structured query:
<QueryList><Query Id="0" Path="system"><Select Path="system">*[((System/Level=1) or
(System/Level=2))]</Select></Query></QueryList>.

ProviderName: Microsoft-Windows-DistributedCOM
TimeCreated Id LevelDisplayName Message
----------- -- ---------------- -------
02.06.2023 06:40:14 10010 Error The server {A463FCB9-6B1C-4E0D-A80B-A2CA7999E25D} did not register with
DCOM ...
02.06.2023 06:38:14 10010 Error The server {A463FCB9-6B1C-4E0D-A80B-A2CA7999E25D} did not register with
DCOM ...
02.06.2023 03:35:23 10010 Error The server {776DBC8D-7347-478C-8D71-791E12EF49D8} did not register with
DCOM ...

PowerShell 技能连载 - 避免使用 Get-EventLog

Get-EventLog 是 Windows PowerShell 中非常受欢迎的 cmdlet。通过仅使用几个简单的参数,它可以从主要的 Windows 事件日志中读取事件日志。然而,这个 cmdlet 使用的技术不仅很慢,而且越来越危险。

Get-EventLog 在查找正确的事件消息时存在困难,所以过去经常得不到有意义的消息。然而,越来越频繁地,Get-EventLog 返回完全无关的错误消息,这可能会触发错误警报。就像这个例子:

1
2
3
4
5
6
PS> Get-EventLog -Source Microsoft-Windows-Kernel-General -Newest 2 -LogName System -InstanceId 1

Index Time EntryType Source InstanceID Message
----- ---- --------- ------ ---------- -------
551590 Jun 01 17:57 Information Microsoft-Windows-Kernel-General 1 Possible detection of CVE: 2023-06-01T15:57:15.025483...
551505 Mai 31 17:57 Information Microsoft-Windows-Kernel-General 1 Possible detection of CVE: 2023-05-31T15:57:13.842816...

CVE 检测是安全问题或入侵的指示器。你可不想成为那个在最后引发混乱的人,结果发现一切只是误报。任何其他工具都会返回相应的事件消息,正如官方替代 Get-EventLog 的工具: Get-WinEvent 也是如此:

1
2
3
4
5
6
7
8
9
10
11
PS> Get-WinEvent -FilterHashtable @{
ProviderName = 'Microsoft-Windows-Kernel-General'
LogName = 'System'
Id = 1
} -MaxEvents 2

ProviderName: Microsoft-Windows-Kernel-General
TimeCreated Id LevelDisplayName Message
----------- -- ---------------- -------
01.06.2023 17:57:15 1 Information The system time has changed to ‎2023‎-‎06‎-‎01T15:57:15.025483100Z from ‎2023‎-‎06‎-‎01T1...
31.05.2023 17:57:13 1 Information The system time has changed to ‎2023‎-‎05‎-‎31T15:57:13.842816200Z from ‎2023‎-‎05‎-‎31T1...

实际上,与 CVE 检测和安全问题不同,系统时间被调整了。

以后在脚本中不要再使用 Get-EventLog(除非你百分之百确定所关心的事件不受其缺点影响),而是要熟悉 Get-WinEvent:它更快、更多功能,并且还可以读取导出的事件文件。