以下脚本适用于PS5_ISE和CMD。
#Just incase Event has been previously registered
Try {
Unregister-Event -SourceIdentifier 'disk' -Force -ErrorAction Stop
}
Catch {}
$REArgs = @{Query = "Select * from __InstanceCreationEvent within 1 where targetinstance isa 'win32_logicaldisk'"
SourceIdentifier = "disk"
Timeout = 1000
}
Register-WmiEvent @REArgs
但是当我尝试在PS7.2.6中运行它时,我得到这个:
PSv7>..testset-wmidisklistener.ps1
Register-WmiEvent: G:BEKDocsScriptstestSet-WMIDiskListener.ps1:11
Line |
11 | Register-WmiEvent @REArgs
| ~~~~~~~~~~~~~~~~~
| The term 'Register-WmiEvent' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of
| the name, or if a path was included, verify that the path is correct and try again.
还。。。
PSv7>get-command Register*
CommandType Name Version Source
----------- ---- ------- ------
Function Register-ClusteredScheduledTask 1.0.0.0 ScheduledTasks
Function Register-DnsClient 1.0.0.0 DnsClient
Function Register-IscsiSession 1.0.0.0 iSCSI
Function Register-PSRepository 2.2.5 PowerShellGet
Function Register-PSRepository 2.2.5 PowerShellGet
Function Register-PSRepository 1.0.0.1 PowerShellGet
Function Register-ScheduledTask 1.0.0.0 ScheduledTasks
Function Register-StorageSubsystem 2.0.0.0 Storage
Cmdlet Register-ArgumentCompleter 7.2.6.500 Microsoft.PowerShell.Core
Cmdlet Register-CimIndicationEvent 7.0.0.0 CimCmdlets
Cmdlet Register-EngineEvent 7.0.0.0 Microsoft.PowerShell.Utility
Cmdlet Register-ObjectEvent 7.0.0.0 Microsoft.PowerShell.Utility
Cmdlet Register-PackageSource 1.4.7 PackageManagement
Cmdlet Register-PSSessionConfiguration 7.2.6.500 Microsoft.PowerShell.Core
Cmdlet Register-ScheduledJob 1.1.0.0 PSScheduledJob
Cmdlet Register-WmiEvent 3.1.0.0 Microsoft.PowerShell.Management
ExternalScript RegisterManifest.ps1 C:Program FilesPowerShell7RegisterManifest.ps1
Application Register-CimProvider.exe 10.0.1904… C:Windowssystem32Register-CimProvider.exe
标准建议适用:
CIM cmdlet(例如,Get-CimInstance
)取代了Windows PowerShell v3(2012年9月发布)中的WMI cmdlet(例如Get-WmiObject
)。
因此,应该避免使用 WMI cmdlet,尤其是因为PowerShell(Core)7+(所有未来的努力都将用于此)甚至不再拥有它们。但是,请注意,WMI 仍然是 CIM cmdlet的基础。有关详细信息,请参阅此答案。
CIM cmdlet 包含在CimCmdlets
模块中。若要全部列出,请运行Get-Command -Module CimCmdlets
虽然 WMI 仍然是 CIM cmdlet的基础,但仅限 Windows PowerShell 的 WMIcmdlet与其 CIM 后继者之间存在差异,这些差异超出了不同的名称,特别是需要使用Invoke-CimMethod
来调用方法。
仅从它的名字来看,Register-CimIndicationEvent
似乎是Register-WmiEvent
的继任者。
至于为什么你在PowerShell(核心)的get-command Register*
输出中看到Register-WmiEvent
:
默认情况下,您不会看到此信息。
仅当您显式选择使用 Windows PowerShell 兼容性功能加载 WindowsPowerShell版本的
Microsoft.PowerShell.Management
模块(其中包含 WMI cmdlet)时,您才会看到它。
(Import-Module -UseWindowsPowerShell Microsoft.PowerShell.Management
)- 但是,鉴于此功能的固有限制(此外,所述模块包含许多PowerShell的核心cmdlet,但没有为PowerShell(核心)中本机存在的那些创建代理)以及CIM cmdlet的本机可用性,这是不明智的。