Can WMI be used to listen the event of formating volume?

Pei Yao-Chang 1 Reputation point
2021-01-07T07:19:02.367+00:00

I want to perform some action once I receive the event of fomating a specific volume, can I use WMI to achieve my goal?

I can use WMI to detect the volume is Arrival or Removal by registering Win32_VolumeChangeEvent class. Below is the example how to use WMI to register Win32_VolumeChangeEvent class and detect volume or device.

#Query for finding all device arrival events
$query = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType=2"

#Register an event subscription
Register-WmiEvent -SourceIdentifier "Qsirch-Monitor-Volume-Add"  -Query $query -MessageData $yao -Action {
    $volumeName = (Get-WMIObject -Class Win32_LogicalDisk -Filter "DeviceID='$($Event.SourceEventArgs.NewEvent.DriveName)'").VolumeName
  Write-Host "$($Event.SourceEventArgs.NewEvent.DriveName) ($($volumeName)) was added"
} | Out-Null
Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,585 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.