PowerShell 技能连载 - 用 Carbon 添加新的 PowerShell 命令

Carbon 是 PowerShell Gallery 中最受欢迎的免费 PowerShell 模块之一。它类似于瑞士军刀,具有多种辅助功能。要安装它,请运行以下命令:

1
PS> Install-Module -Name Carbon -Scope CurrentUser -Force

显然,该模块的所有者添加了有用的功能。这就是测试您的 PowerShell 当前是否处于提升状态所需的全部操作:

1
2
PS> Test-CAdminPrivilege
False

要加密或解密字符串,请使用以下命令:

1
2
3
4
5
6
7
8
9
PS> $secret = "Secret Text" | Protect-CString -ForUser

PS> $secret
AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAf0R6lgTIWkqgPubPNRqOXwAAAAACAAAAAAAQZgAAAAEAACAAAADiVJHgXqE+4kLGfPISsvSg+cBG4m8Q0c5W1nqzl/pHDgAAAAAOgAAAAA
IAACAAAACIF/xsRNBKG2cDnwCACA59JZaeOK/zedzmMrEMML0upxAAAABSmKyvYw4ul+jKW35NZdzmQAAAACE/4MFiRHJVhYOu65P/Vc7hVH5wuUfV0elFtwTfYdN+92h3aguob/Rq
fEANeUZfUotBOE4dxJDdr950rR4ss0I=

PS> $secret | Unprotect-CString
Secret Text

有很多参数可以通过其他方式进行加密,还有大量命令可以发现。显然,模块作者已将其命令名称前面添加了 “C”,也就是 “Carbon” 的意思,并且包括不带前缀的命令名称的别名。

命令的完整列表非常详尽:

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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
PS> Get-Command -Module Carbon


CommandType Name Version Source
----------- ---- ------- ------
Alias Add-GroupMember 2.9.2 Carbon
Alias Add-GroupMembers 2.9.2 Carbon
Alias Add-IisDefaultDocument 2.9.2 Carbon
Alias Add-TrustedHost 2.9.2 Carbon
Alias Add-TrustedHosts 2.9.2 Carbon
Alias Assert-AdminPrivilege 2.9.2 Carbon
Alias Assert-AdminPrivileges 2.9.2 Carbon
Alias Assert-FirewallConfigurable 2.9.2 Carbon
Alias Assert-Service 2.9.2 Carbon
Alias Clear-DscLocalResourceCache 2.9.2 Carbon
Alias Clear-MofAuthoringMetadata 2.9.2 Carbon
Alias Clear-TrustedHost 2.9.2 Carbon
Alias Clear-TrustedHosts 2.9.2 Carbon
Alias Complete-Job 2.9.2 Carbon
Alias Complete-Jobs 2.9.2 Carbon
Alias Compress-Item 2.9.2 Carbon
Alias ConvertFrom-Base64 2.9.2 Carbon
Alias Convert-SecureStringToString 2.9.2 Carbon
Alias ConvertTo-Base64 2.9.2 Carbon
Alias ConvertTo-ContainerInheritanceFlags 2.9.2 Carbon
Alias ConvertTo-FullPath 2.9.2 Carbon
Alias ConvertTo-InheritanceFlag 2.9.2 Carbon
Alias ConvertTo-InheritanceFlags 2.9.2 Carbon
Alias ConvertTo-PropagationFlag 2.9.2 Carbon
Alias ConvertTo-PropagationFlags 2.9.2 Carbon
Alias ConvertTo-SecurityIdentifier 2.9.2 Carbon
Alias Convert-XmlFile 2.9.2 Carbon
Alias Copy-DscResource 2.9.2 Carbon
Alias Disable-AclInheritance 2.9.2 Carbon
Alias Disable-FirewallStatefulFtp 2.9.2 Carbon
Alias Disable-IEEnhancedSecurityConfiguration 2.9.2 Carbon
Alias Disable-IisSecurityAuthentication 2.9.2 Carbon
Alias Disable-NtfsCompression 2.9.2 Carbon
Alias Enable-AclInheritance 2.9.2 Carbon
Alias Enable-FirewallStatefulFtp 2.9.2 Carbon
Alias Enable-IEActivationPermission 2.9.2 Carbon
Alias Enable-IEActivationPermissions 2.9.2 Carbon
Alias Enable-IisDirectoryBrowsing 2.9.2 Carbon
Alias Enable-IisSecurityAuthentication 2.9.2 Carbon
Alias Enable-IisSsl 2.9.2 Carbon
Alias Enable-NtfsCompression 2.9.2 Carbon
Alias Expand-Item 2.9.2 Carbon
Alias Find-ADUser 2.9.2 Carbon
Alias Format-ADSearchFilterValue 2.9.2 Carbon
Alias Format-ADSpecialCharacters 2.9.2 Carbon
Alias Get-ADDomainController 2.9.2 Carbon
Alias Get-Certificate 2.9.2 Carbon
Alias Get-CertificateStore 2.9.2 Carbon
Alias Get-ComPermission 2.9.2 Carbon
Alias Get-ComPermissions 2.9.2 Carbon
Alias Get-ComSecurityDescriptor 2.9.2 Carbon
Alias Get-DscError 2.9.2 Carbon
Alias Get-DscWinEvent 2.9.2 Carbon
Alias Get-FileShare 2.9.2 Carbon
Alias Get-FileSharePermission 2.9.2 Carbon
Alias Get-FirewallRule 2.9.2 Carbon
Alias Get-FirewallRules 2.9.2 Carbon
Alias Get-Group 2.9.2 Carbon
Alias Get-HttpUrlAcl 2.9.2 Carbon
Alias Get-IisApplication 2.9.2 Carbon
Alias Get-IisAppPool 2.9.2 Carbon
Alias Get-IisConfigurationSection 2.9.2 Carbon
Alias Get-IisHttpHeader 2.9.2 Carbon
Alias Get-IisHttpRedirect 2.9.2 Carbon
Alias Get-IisMimeMap 2.9.2 Carbon
Alias Get-IisSecurityAuthentication 2.9.2 Carbon
Alias Get-IisVersion 2.9.2 Carbon
Alias Get-IisWebsite 2.9.2 Carbon
Alias Get-IPAddress 2.9.2 Carbon
Alias Get-Msi 2.9.2 Carbon
Alias Get-MsmqMessageQueue 2.9.2 Carbon
Alias Get-MsmqMessageQueuePath 2.9.2 Carbon
Alias Get-PathCanonicalCase 2.9.2 Carbon
Alias Get-PathProvider 2.9.2 Carbon
Alias Get-PathToHostsFile 2.9.2 Carbon
Alias Get-PerformanceCounter 2.9.2 Carbon
Alias Get-PerformanceCounters 2.9.2 Carbon
Alias Get-Permission 2.9.2 Carbon
Alias Get-Permissions 2.9.2 Carbon
Alias Get-PowerShellModuleInstallPath 2.9.2 Carbon
Alias Get-PowershellPath 2.9.2 Carbon
Alias Get-Privilege 2.9.2 Carbon
Alias Get-Privileges 2.9.2 Carbon
Alias Get-ProgramInstallInfo 2.9.2 Carbon
Alias Get-RegistryKeyValue 2.9.2 Carbon
Alias Get-ScheduledTask 2.9.2 Carbon
Alias Get-ServiceAcl 2.9.2 Carbon
Alias Get-ServiceConfiguration 2.9.2 Carbon
Alias Get-ServicePermission 2.9.2 Carbon
Alias Get-ServicePermissions 2.9.2 Carbon
Alias Get-ServiceSecurityDescriptor 2.9.2 Carbon
Alias Get-SslCertificateBinding 2.9.2 Carbon
Alias Get-SslCertificateBindings 2.9.2 Carbon
Alias Get-TrustedHost 2.9.2 Carbon
Alias Get-TrustedHosts 2.9.2 Carbon
Alias Get-User 2.9.2 Carbon
Alias Get-WmiLocalUserAccount 2.9.2 Carbon
Alias Grant-ComPermission 2.9.2 Carbon
Alias Grant-ComPermissions 2.9.2 Carbon
Alias Grant-HttpUrlPermission 2.9.2 Carbon
Alias Grant-MsmqMessageQueuePermission 2.9.2 Carbon
Alias Grant-MsmqMessageQueuePermissions 2.9.2 Carbon
Alias Grant-Permission 2.9.2 Carbon
Alias Grant-Permissions 2.9.2 Carbon
Alias Grant-Privilege 2.9.2 Carbon
Alias Grant-ServiceControlPermission 2.9.2 Carbon
Alias Grant-ServicePermission 2.9.2 Carbon
Alias Initialize-Lcm 2.9.2 Carbon
Alias Install-Certificate 2.9.2 Carbon
Alias Install-Directory 2.9.2 Carbon
Alias Install-FileShare 2.9.2 Carbon
Alias Install-Group 2.9.2 Carbon
Alias Install-IisApplication 2.9.2 Carbon
Alias Install-IisAppPool 2.9.2 Carbon
Alias Install-IisVirtualDirectory 2.9.2 Carbon
Alias Install-IisWebsite 2.9.2 Carbon
Alias Install-Junction 2.9.2 Carbon
Alias Install-Msi 2.9.2 Carbon
Alias Install-Msmq 2.9.2 Carbon
Alias Install-MsmqMessageQueue 2.9.2 Carbon
Alias Install-PerformanceCounter 2.9.2 Carbon
Alias Install-RegistryKey 2.9.2 Carbon
Alias Install-ScheduledTask 2.9.2 Carbon
Alias Install-Service 2.9.2 Carbon
Alias Install-SmbShare 2.9.2 Carbon
Alias Install-User 2.9.2 Carbon
Alias Invoke-AppCmd 2.9.2 Carbon
Alias Invoke-PowerShell 2.9.2 Carbon
Alias Invoke-WindowsInstaller 2.9.2 Carbon
Alias Join-IisVirtualPath 2.9.2 Carbon
Alias Lock-IisConfigurationSection 2.9.2 Carbon
Alias New-Credential 2.9.2 Carbon
Alias New-Junction 2.9.2 Carbon
Alias New-RsaKeyPair 2.9.2 Carbon
Alias New-TempDir 2.9.2 Carbon
Alias New-TempDirectory 2.9.2 Carbon
Alias Protect-Acl 2.9.2 Carbon
Alias Protect-String 2.9.2 Carbon
Alias Read-File 2.9.2 Carbon
Alias Remove-Certificate 2.9.2 Carbon
Alias Remove-DotNetAppSetting 2.9.2 Carbon
Alias Remove-EnvironmentVariable 2.9.2 Carbon
Alias Remove-GroupMember 2.9.2 Carbon
Alias Remove-HostsEntry 2.9.2 Carbon
Alias Remove-IisMimeMap 2.9.2 Carbon
Alias Remove-IniEntry 2.9.2 Carbon
Alias Remove-Junction 2.9.2 Carbon
Alias Remove-MsmqMessageQueue 2.9.2 Carbon
Alias Remove-RegistryKeyValue 2.9.2 Carbon
Alias Remove-Service 2.9.2 Carbon
Alias Remove-SslCertificateBinding 2.9.2 Carbon
Alias Remove-User 2.9.2 Carbon
Alias Reset-HostsFile 2.9.2 Carbon
Alias Reset-MsmqQueueManagerID 2.9.2 Carbon
Alias Resolve-FullPath 2.9.2 Carbon
Alias Resolve-Identity 2.9.2 Carbon
Alias Resolve-IdentityName 2.9.2 Carbon
Alias Resolve-NetPath 2.9.2 Carbon
Alias Resolve-PathCase 2.9.2 Carbon
Alias Resolve-RelativePath 2.9.2 Carbon
Alias Restart-RemoteService 2.9.2 Carbon
Alias Revoke-ComPermission 2.9.2 Carbon
Alias Revoke-ComPermissions 2.9.2 Carbon
Alias Revoke-HttpUrlPermission 2.9.2 Carbon
Alias Revoke-Permission 2.9.2 Carbon
Alias Revoke-Privilege 2.9.2 Carbon
Alias Revoke-ServicePermission 2.9.2 Carbon
Alias Set-DotNetAppSetting 2.9.2 Carbon
Alias Set-DotNetConnectionString 2.9.2 Carbon
Alias Set-EnvironmentVariable 2.9.2 Carbon
Alias Set-HostsEntry 2.9.2 Carbon
Alias Set-IisHttpHeader 2.9.2 Carbon
Alias Set-IisHttpRedirect 2.9.2 Carbon
Alias Set-IisMimeMap 2.9.2 Carbon
Alias Set-IisWebsiteID 2.9.2 Carbon
Alias Set-IisWebsiteSslCertificate 2.9.2 Carbon
Alias Set-IisWindowsAuthentication 2.9.2 Carbon
Alias Set-IniEntry 2.9.2 Carbon
Alias Set-RegistryKeyValue 2.9.2 Carbon
Alias Set-ServiceAcl 2.9.2 Carbon
Alias Set-SslCertificateBinding 2.9.2 Carbon
Alias Set-TrustedHost 2.9.2 Carbon
Alias Set-TrustedHosts 2.9.2 Carbon
Alias Split-Ini 2.9.2 Carbon
Alias Start-DscPullConfiguration 2.9.2 Carbon
Alias Test-AdminPrivilege 2.9.2 Carbon
Alias Test-AdminPrivileges 2.9.2 Carbon
Alias Test-DotNet 2.9.2 Carbon
Alias Test-DscTargetResource 2.9.2 Carbon
Alias Test-FileShare 2.9.2 Carbon
Alias Test-FirewallStatefulFtp 2.9.2 Carbon
Alias Test-Group 2.9.2 Carbon
Alias Test-GroupMember 2.9.2 Carbon
Alias Test-Identity 2.9.2 Carbon
Alias Test-IisAppPool 2.9.2 Carbon
Alias Test-IisConfigurationSection 2.9.2 Carbon
Alias Test-IisSecurityAuthentication 2.9.2 Carbon
Alias Test-IisWebsite 2.9.2 Carbon
Alias Test-IPAddress 2.9.2 Carbon
Alias Test-MsmqMessageQueue 2.9.2 Carbon
Alias Test-NtfsCompression 2.9.2 Carbon
Alias Test-OSIs32Bit 2.9.2 Carbon
Alias Test-OSIs64Bit 2.9.2 Carbon
Alias Test-PathIsJunction 2.9.2 Carbon
Alias Test-PerformanceCounter 2.9.2 Carbon
Alias Test-PerformanceCounterCategory 2.9.2 Carbon
Alias Test-Permission 2.9.2 Carbon
Alias Test-PowerShellIs32Bit 2.9.2 Carbon
Alias Test-PowerShellIs64Bit 2.9.2 Carbon
Alias Test-Privilege 2.9.2 Carbon
Alias Test-RegistryKeyValue 2.9.2 Carbon
Alias Test-ScheduledTask 2.9.2 Carbon
Alias Test-Service 2.9.2 Carbon
Alias Test-SslCertificateBinding 2.9.2 Carbon
Alias Test-TypeDataMember 2.9.2 Carbon
Alias Test-UncPath 2.9.2 Carbon
Alias Test-User 2.9.2 Carbon
Alias Test-WindowsFeature 2.9.2 Carbon
Alias Test-ZipFile 2.9.2 Carbon
Alias Uninstall-Certificate 2.9.2 Carbon
Alias Uninstall-Directory 2.9.2 Carbon
Alias Uninstall-FileShare 2.9.2 Carbon
Alias Uninstall-Group 2.9.2 Carbon
Alias Uninstall-IisAppPool 2.9.2 Carbon
Alias Uninstall-IisWebsite 2.9.2 Carbon
Alias Uninstall-Junction 2.9.2 Carbon
Alias Uninstall-MsmqMessageQueue 2.9.2 Carbon
Alias Uninstall-PerformanceCounterCategory 2.9.2 Carbon
Alias Uninstall-ScheduledTask 2.9.2 Carbon
Alias Uninstall-Service 2.9.2 Carbon
Alias Uninstall-User 2.9.2 Carbon
Alias Unlock-IisConfigurationSection 2.9.2 Carbon
Alias Unprotect-AclAccessRules 2.9.2 Carbon
Alias Unprotect-String 2.9.2 Carbon
Alias Write-DscError 2.9.2 Carbon
Alias Write-File 2.9.2 Carbon
Function Add-CGroupMember 2.9.2 Carbon
Function Add-CTrustedHost 2.9.2 Carbon
Function Assert-CAdminPrivilege 2.9.2 Carbon
Function Assert-CFirewallConfigurable 2.9.2 Carbon
Function Assert-CService 2.9.2 Carbon
Function Clear-CDscLocalResourceCache 2.9.2 Carbon
Function Clear-CMofAuthoringMetadata 2.9.2 Carbon
Function Clear-CTrustedHost 2.9.2 Carbon
Function Complete-CJob 2.9.2 Carbon
Function Compress-CItem 2.9.2 Carbon
Function Convert-CSecureStringToString 2.9.2 Carbon
Function Convert-CXmlFile 2.9.2 Carbon
Function ConvertFrom-CBase64 2.9.2 Carbon
Function ConvertTo-CBase64 2.9.2 Carbon
Function ConvertTo-CContainerInheritanceFlags 2.9.2 Carbon
Function ConvertTo-CInheritanceFlag 2.9.2 Carbon
Function ConvertTo-CPropagationFlag 2.9.2 Carbon
Function ConvertTo-CSecurityIdentifier 2.9.2 Carbon
Function Copy-CDscResource 2.9.2 Carbon
Function Disable-CAclInheritance 2.9.2 Carbon
Function Disable-CFirewallStatefulFtp 2.9.2 Carbon
Function Disable-CIEEnhancedSecurityConfiguration 2.9.2 Carbon
Function Disable-CNtfsCompression 2.9.2 Carbon
Function Enable-CAclInheritance 2.9.2 Carbon
Function Enable-CFirewallStatefulFtp 2.9.2 Carbon
Function Enable-CIEActivationPermission 2.9.2 Carbon
Function Enable-CNtfsCompression 2.9.2 Carbon
Function Expand-CItem 2.9.2 Carbon
Function Find-CADUser 2.9.2 Carbon
Function Format-CADSearchFilterValue 2.9.2 Carbon
Function Get-CADDomainController 2.9.2 Carbon
Function Get-CCertificate 2.9.2 Carbon
Function Get-CCertificateStore 2.9.2 Carbon
Function Get-CComPermission 2.9.2 Carbon
Function Get-CComSecurityDescriptor 2.9.2 Carbon
Function Get-CDscError 2.9.2 Carbon
Function Get-CDscWinEvent 2.9.2 Carbon
Function Get-CFileShare 2.9.2 Carbon
Function Get-CFileSharePermission 2.9.2 Carbon
Function Get-CFirewallRule 2.9.2 Carbon
Function Get-CGroup 2.9.2 Carbon
Function Get-CHttpUrlAcl 2.9.2 Carbon
Function Get-CIPAddress 2.9.2 Carbon
Function Get-CMsi 2.9.2 Carbon
Function Get-CMsmqMessageQueue 2.9.2 Carbon
Function Get-CMsmqMessageQueuePath 2.9.2 Carbon
Function Get-CPathProvider 2.9.2 Carbon
Function Get-CPathToHostsFile 2.9.2 Carbon
Function Get-CPerformanceCounter 2.9.2 Carbon
Function Get-CPermission 2.9.2 Carbon
Function Get-CPowerShellModuleInstallPath 2.9.2 Carbon
Function Get-CPowershellPath 2.9.2 Carbon
Function Get-CPrivilege 2.9.2 Carbon
Function Get-CProgramInstallInfo 2.9.2 Carbon
Function Get-CRegistryKeyValue 2.9.2 Carbon
Function Get-CScheduledTask 2.9.2 Carbon
Function Get-CServiceAcl 2.9.2 Carbon
Function Get-CServiceConfiguration 2.9.2 Carbon
Function Get-CServicePermission 2.9.2 Carbon
Function Get-CServiceSecurityDescriptor 2.9.2 Carbon
Function Get-CSslCertificateBinding 2.9.2 Carbon
Function Get-CTrustedHost 2.9.2 Carbon
Function Get-CUser 2.9.2 Carbon
Function Get-CWmiLocalUserAccount 2.9.2 Carbon
Function Grant-CComPermission 2.9.2 Carbon
Function Grant-CHttpUrlPermission 2.9.2 Carbon
Function Grant-CMsmqMessageQueuePermission 2.9.2 Carbon
Function Grant-CPermission 2.9.2 Carbon
Function Grant-CPrivilege 2.9.2 Carbon
Function Grant-CServiceControlPermission 2.9.2 Carbon
Function Grant-CServicePermission 2.9.2 Carbon
Function Initialize-CLcm 2.9.2 Carbon
Function Install-CCertificate 2.9.2 Carbon
Function Install-CDirectory 2.9.2 Carbon
Function Install-CFileShare 2.9.2 Carbon
Function Install-CGroup 2.9.2 Carbon
Function Install-CJunction 2.9.2 Carbon
Function Install-CMsi 2.9.2 Carbon
Function Install-CMsmq 2.9.2 Carbon
Function Install-CMsmqMessageQueue 2.9.2 Carbon
Function Install-CPerformanceCounter 2.9.2 Carbon
Function Install-CRegistryKey 2.9.2 Carbon
Function Install-CScheduledTask 2.9.2 Carbon
Function Install-CService 2.9.2 Carbon
Function Install-CUser 2.9.2 Carbon
Function Invoke-CAppCmd 2.9.2 Carbon
Function Invoke-CPowerShell 2.9.2 Carbon
Function New-CCredential 2.9.2 Carbon
Function New-CJunction 2.9.2 Carbon
Function New-CRsaKeyPair 2.9.2 Carbon
Function New-CTempDirectory 2.9.2 Carbon
Function Read-CFile 2.9.2 Carbon
Function Remove-CDotNetAppSetting 2.9.2 Carbon
Function Remove-CEnvironmentVariable 2.9.2 Carbon
Function Remove-CGroupMember 2.9.2 Carbon
Function Remove-CHostsEntry 2.9.2 Carbon
Function Remove-CIniEntry 2.9.2 Carbon
Function Remove-CJunction 2.9.2 Carbon
Function Remove-CRegistryKeyValue 2.9.2 Carbon
Function Remove-CSslCertificateBinding 2.9.2 Carbon
Function Reset-CHostsFile 2.9.2 Carbon
Function Reset-CMsmqQueueManagerID 2.9.2 Carbon
Function Resolve-CFullPath 2.9.2 Carbon
Function Resolve-CIdentity 2.9.2 Carbon
Function Resolve-CIdentityName 2.9.2 Carbon
Function Resolve-CNetPath 2.9.2 Carbon
Function Resolve-CPathCase 2.9.2 Carbon
Function Resolve-CRelativePath 2.9.2 Carbon
Function Restart-CRemoteService 2.9.2 Carbon
Function Revoke-CComPermission 2.9.2 Carbon
Function Revoke-CHttpUrlPermission 2.9.2 Carbon
Function Revoke-CPermission 2.9.2 Carbon
Function Revoke-CPrivilege 2.9.2 Carbon
Function Revoke-CServicePermission 2.9.2 Carbon
Function Set-CDotNetAppSetting 2.9.2 Carbon
Function Set-CDotNetConnectionString 2.9.2 Carbon
Function Set-CEnvironmentVariable 2.9.2 Carbon
Function Set-CHostsEntry 2.9.2 Carbon
Function Set-CIniEntry 2.9.2 Carbon
Function Set-CRegistryKeyValue 2.9.2 Carbon
Function Set-CServiceAcl 2.9.2 Carbon
Function Set-CSslCertificateBinding 2.9.2 Carbon
Function Set-CTrustedHost 2.9.2 Carbon
Function Split-CIni 2.9.2 Carbon
Function Start-CDscPullConfiguration 2.9.2 Carbon
Function Test-CAdminPrivilege 2.9.2 Carbon
Function Test-CDotNet 2.9.2 Carbon
Function Test-CDscTargetResource 2.9.2 Carbon
Function Test-CFileShare 2.9.2 Carbon
Function Test-CFirewallStatefulFtp 2.9.2 Carbon
Function Test-CGroup 2.9.2 Carbon
Function Test-CGroupMember 2.9.2 Carbon
Function Test-CIdentity 2.9.2 Carbon
Function Test-CIPAddress 2.9.2 Carbon
Function Test-CMsmqMessageQueue 2.9.2 Carbon
Function Test-CNtfsCompression 2.9.2 Carbon
Function Test-COSIs32Bit 2.9.2 Carbon
Function Test-COSIs64Bit 2.9.2 Carbon
Function Test-CPathIsJunction 2.9.2 Carbon
Function Test-CPerformanceCounter 2.9.2 Carbon
Function Test-CPerformanceCounterCategory 2.9.2 Carbon
Function Test-CPermission 2.9.2 Carbon
Function Test-CPowerShellIs32Bit 2.9.2 Carbon
Function Test-CPowerShellIs64Bit 2.9.2 Carbon
Function Test-CPrivilege 2.9.2 Carbon
Function Test-CRegistryKeyValue 2.9.2 Carbon
Function Test-CScheduledTask 2.9.2 Carbon
Function Test-CService 2.9.2 Carbon
Function Test-CSslCertificateBinding 2.9.2 Carbon
Function Test-CTypeDataMember 2.9.2 Carbon
Function Test-CUncPath 2.9.2 Carbon
Function Test-CUser 2.9.2 Carbon
Function Test-CWindowsFeature 2.9.2 Carbon
Function Test-CZipFile 2.9.2 Carbon
Function Uninstall-CCertificate 2.9.2 Carbon
Function Uninstall-CDirectory 2.9.2 Carbon
Function Uninstall-CFileShare 2.9.2 Carbon
Function Uninstall-CGroup 2.9.2 Carbon
Function Uninstall-CJunction 2.9.2 Carbon
Function Uninstall-CMsmqMessageQueue 2.9.2 Carbon
Function Uninstall-CPerformanceCounterCategory 2.9.2 Carbon
Function Uninstall-CScheduledTask 2.9.2 Carbon
Function Uninstall-CService 2.9.2 Carbon
Function Uninstall-CUser 2.9.2 Carbon
Function Write-CDscError 2.9.2 Carbon
Function Write-CFile 2.9.2 Carbon
Filter Protect-CString 2.9.2 Carbon
Filter Unprotect-CString 2.9.2 Carbon

PowerShell 技能连载 - 使用 PSWindowsUpdate 管理更新

在 PowerShell Gallery 中有许多有用的 PowerShell 模块。有一个能帮助您管理更新。要下载和安装它,请运行:

1
PS> Install-Module -Name PSWindowsUpdate -Scope CurrentUser -Force

它添加了一系列与 Windows Update 相关的新命令:

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
PS> Get-Command -Module PSWindowsUpdate

CommandType Name Version Source
----------- ---- ------- ------
Alias Clear-WUJob 2.1.1.2 PSWindowsUpdate
Alias Download-WindowsUpdate 2.1.1.2 PSWindowsUpdate
Alias Get-WUInstall 2.1.1.2 PSWindowsUpdate
Alias Get-WUList 2.1.1.2 PSWindowsUpdate
Alias Hide-WindowsUpdate 2.1.1.2 PSWindowsUpdate
Alias Install-WindowsUpdate 2.1.1.2 PSWindowsUpdate
Alias Show-WindowsUpdate 2.1.1.2 PSWindowsUpdate
Alias UnHide-WindowsUpdate 2.1.1.2 PSWindowsUpdate
Alias Uninstall-WindowsUpdate 2.1.1.2 PSWindowsUpdate
Cmdlet Add-WUServiceManager 2.1.1.2 PSWindowsUpdate
Cmdlet Enable-WURemoting 2.1.1.2 PSWindowsUpdate
Cmdlet Get-WindowsUpdate 2.1.1.2 PSWindowsUpdate
Cmdlet Get-WUApiVersion 2.1.1.2 PSWindowsUpdate
Cmdlet Get-WUHistory 2.1.1.2 PSWindowsUpdate
Cmdlet Get-WUInstallerStatus 2.1.1.2 PSWindowsUpdate
Cmdlet Get-WUJob 2.1.1.2 PSWindowsUpdate
Cmdlet Get-WULastResults 2.1.1.2 PSWindowsUpdate
Cmdlet Get-WURebootStatus 2.1.1.2 PSWindowsUpdate
Cmdlet Get-WUServiceManager 2.1.1.2 PSWindowsUpdate
Cmdlet Get-WUSettings 2.1.1.2 PSWindowsUpdate
Cmdlet Invoke-WUJob 2.1.1.2 PSWindowsUpdate
Cmdlet Remove-WindowsUpdate 2.1.1.2 PSWindowsUpdate
Cmdlet Remove-WUServiceManager 2.1.1.2 PSWindowsUpdate
Cmdlet Set-PSWUSettings 2.1.1.2 PSWindowsUpdate
Cmdlet Set-WUSettings 2.1.1.2 PSWindowsUpdate
Cmdlet Update-WUModule 2.1.1.2 PSWindowsUpdate

大多数命令需要提升权限的 shell 才能正常工作,但每个人都可以获得基本信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PS> Get-WULastResults
WARNING: To perform some operations you must run an elevated Windows PowerShell console.

ComputerName LastSearchSuccessDate LastInstallationSuccessDate
------------ --------------------- ---------------------------
DESKTOP-8DVNI43 22.01.2020 11:29:24 22.01.2020 11:29:52



PS> Get-WUApiVersion
WARNING: To perform some operations you must run an elevated Windows PowerShell console.

ComputerName PSWindowsUpdate PSWUModuleDll ApiVersion WuapiDllVersion
------------ --------------- ------------- ---------- ---------------
DESKTOP-8... 2.1.1.2 2.0.6995.28496 8.0 10.0.18362.387

PowerShell 技能连载 - PowerShell 技能连载 - 动态参数完成(第 5 部分)

在前面的技能中,我们研究了完成应用程序路径的复杂的完成代码。收集完成值可能需要一些时间,并且有可能使 IntelliSense 超时。对于不太可能更改的完成值,最好先计算一次,然后再使用缓存的值。

通过这种方式,安装自动完成器可能会占用一两秒时间,但是在那之后就可以享受快速的 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
# define a function without argument completer
function Start-Software {
param(
[Parameter(Mandatory)]
[string]
$Path
)

Start-Process -FilePath $Path
}

# define the code used for completing application paths
$code = {


}

# calculate the completion values once, and reuse the values later
# store results in a script-global variable
$script:applicationCompleter = & {
# get registered applications from registry
$key = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*"

[System.Collections.Generic.List[string]]$list =
Get-ItemProperty -Path $key |
Select-Object -ExpandProperty '(Default)' -ErrorAction Ignore

# add applications found by Get-Command
[System.Collections.Generic.List[string]]$commands =
Get-Command -CommandType Application |
Select-Object -ExpandProperty Source
$list.AddRange($commands)

# add descriptions and compose completionresult entries
$list |
# remove empty paths
Where-Object { $_ } |
# remove quotes and turn to lower case
ForEach-Object { $_.Replace('"','').Trim().ToLower() } |
# remove duplicate paths
Sort-Object -Unique |
ForEach-Object {
# skip files that do not exist
if ( (Test-Path -Path $_))
{
# get file details
$file = Get-Item -Path $_
# quote path if it has spaces
$path = $_
if ($path -like '* *') { $path = "'$path'" }
# make sure tooltip is not null
$tooltip = [string]$file.VersionInfo.FileDescription
if ([string]::IsNullOrEmpty($tooltip)) { $tooltip = $file.Name }
# compose completion result
[Management.Automation.CompletionResult]::new(
# complete path
$path,
# show friendly text in IntelliSense menu
('{0} ({1})' -f $tooltip, $file.Name),
# use file icon
'ProviderItem',
# show file description
$tooltip
)
}
}
}

# instead of complex code, simply return the cached results when needed
$code = { $script:applicationCompleter }

# tie the completer code to all applicable parameters of own or foreign commands
Register-ArgumentCompleter -CommandName Start-Software -ParameterName Path -ScriptBlock $code
Register-ArgumentCompleter -CommandName Start-Process -ParameterName FilePath -ScriptBlock $code

当您运行上面的代码然后使用 Start-SoftwareStart-Process 命令时,您将获得高度响应的 IntelliSense。与内置的完成功能相反,您需要手动按 CTRL + SPACE。

PowerShell 技能连载 - 动态参数完成(第 4 部分)

在上一个技能中,我们解释了如何使用 [ArgumentCompleter] 为参数添加功能强大的参数完成器。但是有一些限制:

  • 当完成代码变得复杂时,您的代码将变得难以阅读
  • 您不能将参数完成添加到现有命令。[ArgumentCompleter] 属性仅适用于您自己的函数。

但是,实际上,该属性只是将参数完成程序代码添加到 PowerShell 的两种方法之一。您也可以使用 Register-ArgumentCompleter 并将代码添加到现有命令中。

让我们首先看一下先前技巧中的示例:

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
function Start-Software {
param(
[Parameter(Mandatory)]
[ArgumentCompleter({


# get registered applications from registry
$key = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*"

[System.Collections.Generic.List[string]]$list =
Get-ItemProperty -Path $key |
Select-Object -ExpandProperty '(Default)' -ErrorAction Ignore

# add applications found by Get-Command
[System.Collections.Generic.List[string]]$commands =
Get-Command -CommandType Application |
Select-Object -ExpandProperty Source
$list.AddRange($commands)

# add descriptions and compose completion result entries
$list |
# remove empty paths
Where-Object { $_ } |
# remove quotes and turn to lower case
ForEach-Object { $_.Replace('"','').Trim().ToLower() } |
# remove duplicate paths
Sort-Object -Unique |
ForEach-Object {
# skip files that do not exist
if ( (Test-Path -Path $_))
{
# get file details
$file = Get-Item -Path $_
# quote path if it has spaces
$path = $_
if ($path -like '* *') { $path = "'$path'" }
# make sure tooltip is not null
$tooltip = [string]$file.VersionInfo.FileDescription
if ([string]::IsNullOrEmpty($tooltip)) { $tooltip = $file.Name }
# compose completion result
[Management.Automation.CompletionResult]::new(
# complete path
$path,
# show friendly text in IntelliSense menu
('{0} ({1})' -f $tooltip, $file.Name),
# use file icon
'ProviderItem',
# show file description
$tooltip
)
}
}

})]
[string]
$Path
)

Start-Process -FilePath $Path
}

函数 Start-Software 使用 [ArgumentCompleter] 属性定义了参数完成器,并且当使用 Start-Software 时,能获得 -Path 参数丰富的完成信息。

以下是一种替代方法,可以将完成程序代码单独发送到 PowerShell,而不使用属性。而是使用 Register-ArgumentCompleter 将完成程序代码绑定到任何命令的任何参数:

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
# define a function without argument completer
function Start-Software {
param(
[Parameter(Mandatory)]
[string]
$Path
)

Start-Process -FilePath $Path
}

# define the code used for completing application paths
$code = {

# get registered applications from registry
$key = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*"

[System.Collections.Generic.List[string]]$list =
Get-ItemProperty -Path $key |
Select-Object -ExpandProperty '(Default)' -ErrorAction Ignore

# add applications found by Get-Command
[System.Collections.Generic.List[string]]$commands =
Get-Command -CommandType Application |
Select-Object -ExpandProperty Source
$list.AddRange($commands)

# add descriptions and compose completionresult entries
$list |
# remove empty paths
Where-Object { $_ } |
# remove quotes and turn to lower case
ForEach-Object { $_.Replace('"','').Trim().ToLower() } |
# remove duplicate paths
Sort-Object -Unique |
ForEach-Object {
# skip files that do not exist
if ( (Test-Path -Path $_))
{
# get file details
$file = Get-Item -Path $_
# quote path if it has spaces
$path = $_
if ($path -like '* *') { $path = "'$path'" }
# make sure tooltip is not null
$tooltip = [string]$file.VersionInfo.FileDescription
if ([string]::IsNullOrEmpty($tooltip)) { $tooltip = $file.Name }
# compose completion result
[Management.Automation.CompletionResult]::new(
# complete path
$path,
# show friendly text in IntelliSense menu
('{0} ({1})' -f $tooltip, $file.Name),
# use file icon
'ProviderItem',
# show file description
$tooltip
)
}
}
}

# tie the completer code to all applicable parameters of own or foreign commands
Register-ArgumentCompleter -CommandName Start-Software -ParameterName Path -ScriptBlock $code
Register-ArgumentCompleter -CommandName Start-Process -ParameterName FilePath -ScriptBlock $code

现在,您自己的 Start-Software 函数的 -Path 参数和内置 cmdlet Start-Process 功能参数完成的 -FilePath 参数。完成代码可以重复利用。

注意:根据计算机上安装的软件和驱动器的速度,此示例中的完成代码可能需要一些时间才能执行。如果 IntelliSense 菜单超时,请按 CTRL + SPACE 再试一次。

PowerShell 技能连载 - 动态参数完成(第 3 部分)

根据我们过去讨论的技巧,让我们编写一个有用的最终代码,以列出所有可以启动的程序:

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
function Start-Software {
param(
[Parameter(Mandatory)]
[ArgumentCompleter({


# get registered applications from registry
$key = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*"

[System.Collections.Generic.List[string]]$list =
Get-ItemProperty -Path $key |
Select-Object -ExpandProperty '(Default)' -ErrorAction Ignore

# add applications found by Get-Command
[System.Collections.Generic.List[string]]$commands =
Get-Command -CommandType Application |
Select-Object -ExpandProperty Source
$list.AddRange($commands)

# add descriptions and compose completionresult entries
$list |
# remove empty paths
Where-Object { $_ } |
# remove quotes and turn to lower case
ForEach-Object { $_.Replace('"','').Trim().ToLower() } |
# remove duplicate paths
Sort-Object -Unique |
ForEach-Object {
# skip files that do not exist
if ( (Test-Path -Path $_))
{
# get file details
$file = Get-Item -Path $_
# quote path if it has spaces
$path = $_
if ($path -like '* *') { $path = "'$path'" }
# make sure tooltip is not null
$tooltip = [string]$file.VersionInfo.FileDescription
if ([string]::IsNullOrEmpty($tooltip)) { $tooltip = $file.Name }
# compose completion result
[Management.Automation.CompletionResult]::new(
# complete path
$path,
# show friendly text in IntelliSense menu
('{0} ({1})' -f $tooltip, $file.Name),
# use file icon
'ProviderItem',
# show file description
$tooltip
)
}
}

})]
[string]
$Path
)

Start-Process -FilePath $Path
}

当您运行上述代码然后调用 Start-Software 时,请按 CTRL + SPACE,以使用简称来查看可用应用程序的完整列表。选择一个后,将自动完成绝对路径。路径包含空格时将自动加上单引号。

请注意,您可以先输入一些字符,例如 exc,然后按 CTRL + SPACE。这将预过滤 IntelliSense 列表。

另请注意:根据计算机上安装的软件和驱动器的速度,此示例中的完成代码可能需要一些时间才能执行。如果 IntelliSense 菜单超时,请按 CTRL + SPACE 再试一次。

PowerShell 技能连载 - 动态参数完成(第 2 部分)

在前面的技巧中,我们研究了 [ArgumentCompleter] 以及此属性如何将聪明的代码添加到为参数提供自动完成值的参数。自动完成功能甚至可以做更多的事情:您可以根据实际情况生成 IntelliSense 菜单。

请看这段代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function Get-OU {
param(
[Parameter(Mandatory)]
[ArgumentCompleter({

[Management.Automation.CompletionResult]::new("'OU=managers,DC=company,DC=local'", "Management", "ProviderItem", "OU where the Management lives")
[Management.Automation.CompletionResult]::new("'OU=subtest,OU=test,DC=company,DC=local'", "Experimental", "DynamicKeyword", "Reserved")
[Management.Automation.CompletionResult]::new("'OU=External,OU=IT,DC=company,DC=local'", "Help Desk", "ProviderItem", "OU where the Helpdesk people reside")

})]
[string]
$OU
)

"Chosen path: $OU"
}

完整代码基本上只创建三个新的CompletionResult对象。每个参数都有四个参数:

  • 自动完成的文字
  • 显示在 IntelliSense 菜单中的文字
  • IntelliSense 菜单的图标
  • IntelliSense 菜单的工具提示

您甚至可以控制 IntelliSense 菜单中显示的图标。这些是预定义的图标:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PS> [Enum]::GetNames([System.Management.Automation.CompletionResultType])
Text
History
Command
ProviderItem
ProviderContainer
Property
Method
ParameterName
ParameterValue
Variable
Namespace
Type
Keyword
DynamicKeyword

当您运行此代码然后调用 Get-OU 时,可以按 TAB 键完成 OU X500 路径,也可以按 CTRL + SPACE 打开 IntelliSense 菜单。在菜单内,您会看到所选的图标和友好的文本。选择项目后,将使用 X500 自动完成的文字。

PowerShell 技能连载 - 动态参数完成(第 1 部分)

在前面的技巧中,我们介绍了将参数完成符添加到参数的各种方法。一种方法是使用 [ArgumentCompleter] 属性,如下所示:如您所见,这仅是完善补全代码的问题:当文件名包含空格时,表达式放在引号内,否则不用。如果希望完成者仅返回文件并忽略文件夹,则将 -File 参数添加到 Get-ChildItem

1
2
3
4
5
6
7
8
9
10
function Get-File {
param(
[Parameter(Mandatory)]
[ArgumentCompleter({Get-ChildItem -Path $env:windir -Name})]
[string]
$FileName
)

"Chosen file name: $FileName"
}

本质上,运行此代码然后调用 Get-File 时,一旦使用 -FileName 参数,就可以按 TAB 或 CTRL + SPACE 自动列出 Windows 文件夹中所有文件的文件名。 PowerShell执行 [ArgumentCompleter] 中定义的脚本块以动态计算出自动完成的列表。

有一个反馈称,完成后,这些值需要检查特殊字符(例如空格),并在必要时用引号将它包裹起来。让我们听取这些反馈意见,看看如何改进自动完成代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function Get-File {
param(
[Parameter(Mandatory)]
[ArgumentCompleter({
Get-ChildItem -Path $env:windir -Name |
ForEach-Object {
if ($_ -like '* *')
{
"'$_'"
}
else
{
$_
}
}

})]
[string]
$FileName
)

"Chosen file name: $FileName"
}

如您所见,这完全是完善补全代码的问题:当文件名包含空格时,表达式需要放在引号内,否则就不需要。如果希望完成者仅返回文件并忽略文件夹,则将 -File 参数添加到 Get-ChildItem

PowerShell 技能连载 - 列出安装的应用程序(第 2 部分)

在上一个技能中,我们读取了注册表,以查找可以启动的应用程序的路径。这种方法效果很好,但存在两个缺陷:首先,列表不包含应用程序的友好名称,其次,列表不完整。仅列出已注册的程序。

让我们获得完整的应用程序列表,并使用三个技巧来克服这些限制:

  • 使用 generic list 作为结果,以便能够将更多信息快速添加到列表中
  • Get-Command 的结果合并到 PowerShell 已知的应用程序中
  • 读取扩展文件信息得到应用程序友好名称

我们从这里开始:从注册表中注册的应用程序列表:

1
2
3
4
5
6
7
8
$key = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*"

[System.Collections.Generic.List[string]]$list =
Get-ItemProperty -Path $key |
Select-Object -ExpandProperty '(Default)' -ErrorAction Ignore

$list

现在,我们将 Get-Command 已知的应用程序添加到列表中:

1
2
3
4
5
[System.Collections.Generic.List[string]]$commands =
Get-Command -CommandType Application |
Select-Object -ExpandProperty Source

$list.AddRange($commands)

最后,删除引号,空的和重复的项目来清理列表:

1
2
3
4
$finalList = $list |
Where-Object { $_ } |
ForEach-Object { $_.Replace('"','').Trim().ToLower() } |
Sort-Object -Unique

现在,通过读取每个文件的扩展信息,将列表变成具有应用程序名称、描述和绝对路径的对象。这也消除了所有不存在的路径。以下是完整的代码:

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
$key = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*"

[System.Collections.Generic.List[string]]$list =
Get-ItemProperty -Path $key |
Select-Object -ExpandProperty '(Default)' -ErrorAction Ignore

[System.Collections.Generic.List[string]]$commands = Get-Command -CommandType Application |
Select-Object -ExpandProperty Source

$list.AddRange($commands)

$finalList = $list |
Where-Object { $_ } |
ForEach-Object { $_.Replace('"','').Trim().ToLower() } |
Sort-Object -Unique |
ForEach-Object {
try {
$file = Get-Item -Path $_ -ErrorAction Ignore
[PSCustomObject]@{
Name = $file.Name
Description = $file.VersionInfo.FileDescription
Path = $file.FullName
}
} catch {}
} |
Sort-Object -Property Name -Unique

$finalList | Out-GridView -PassThru

结果类似这样:

1
2
3
4
5
6
7
8
9
PS> $finalList

Name Description
---- -----------
7zfm.exe 7-Zip File Manager
accicons.exe Microsoft Office component
acrord32.exe Adobe Acrobat Reader DC
agentservice.exe AgentService EXE
aitstatic.exe Application Impact Telemetry...

PowerShell 技能连载 - 列出安装的应用程序(第 1 部分)

是否想知道启动一个应用程序的运行路径?Windows 注册表中有存储以下信息的键:

1
2
3
4
5
6
7
$key = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*"

$lookup = Get-ItemProperty -Path $key |
Select-Object -ExpandProperty '(Default)' -ErrorAction Ignore |
Where-Object { $_ } |
Sort-Object

结果是已注册的应用程序路径的排序列表。您可以轻松地将其转换为查找哈希表,该表根据可执行文件名称查询完整路径:

1
2
3
4
5
6
7
8
9
$key = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*",
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\*"

$lookup = Get-ItemProperty -Path $key |
Select-Object -ExpandProperty '(Default)' -ErrorAction Ignore |
Where-Object { $_ } |
Group-Object -Property {
$_.Replace('"','').Split('\')[-1].ToLower()
} -AsHashTable -AsString

您现在可以列出所有已注册的应用程序的清单:

1
2
3
4
5
6
7
PS> $lookup.Keys
outlook.exe
winword.exe
snagit32.exe
7zfm.exe
msoasb.exe
...

或者您可以可以将可执行文件的路径转换为它的真实路径:

1
2
PS> $lookup['excel.exe']
C:\Program Files (x86)\Microsoft Office\Root\Office16\EXCEL.EXE

PowerShell 技能连载 - 神秘的动态参数完成器

在上一个技能中,我们介绍了鲜为人知的 “ArgumentCompletion“ 属性,该属性可以为参数提供类似 IntelliSense 的自动完成功能。但是,此属性可以做的更多。之前,我们介绍了以下代码:

1
2
3
4
5
6
7
8
9
10
function Get-Vendor {
param(
[Parameter(Mandatory)]
[ArgumentCompleter({'Microsoft','Amazon','Google'})]
[string]
$Vendor
)

"Chosen vendor: $Vendor"
}

当用户调用 Get-Vendor 时,通过按 TAB 或 CTRL-SHIFT 键,将显示 “ArgumentCompleter“ 属性中列出的建议。

您可能想知道为什么将字符串列表嵌入大括号(脚本块)中。答案是:因为这段代码实际上是在用户调用完成时执行的。您也可以动态生成该自动完成文本。

这个 Submit-Date 函数具有一个称为 -Date 的参数。每当您按 TAB 键时,自动完成程序都会以引用的 ISO 格式完成当前日期和时间:

1
2
3
4
5
6
7
8
9
10
function Submit-Date {
param(
[Parameter(Mandatory)]
[ArgumentCompleter({ '"{0}"' -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss") })]
[DateTime]
$Date
)

"Chosen date: $Date"
}

运行代码来试验效果。接下来,输入 Submit-Date,以及一个空格,然后按 TAB 键。

1
PS> Submit-Date -Date "2020-01-21 16:33:19"

同样,下一个函数实现 -FileName 参数,当您按 TAB 键时,它将自动完成 Windows 文件夹中的实际文件名:

1
2
3
4
5
6
7
8
9
10
11
12
function Get-File {
param(
[Parameter(Mandatory)]
[ArgumentCompleter({Get-ChildItem -Path $env:windir -Name})]
[string]
$FileName
)

"Chosen file name: $FileName"
}

Get-File -FileName

每当用户通过按 TAB 或 CTRL-SPACE 调用自动完成功能时,都会执行提交到 ArgumentCompleter 的脚本块中的代码,并将结果用于自动完成功能。

这可能就是为什么 AutoCompleter 属性不会自动弹出 IntelliSense 而是仅响应用户请求自动弹出的原因。请注意,自动完成功能可能无法在编辑器窗格中使用。它是为交互式PowerShell控制台设计的。