我打算运行此脚本来收集有关磁盘的信息。当我插入USB设备时,它应显示名称,字母,序列号。问题是当插入新的USB设备时,脚本会重新显示之前插入的所有磁盘的信息,而不仅仅是最后一个。
Register-WmiEvent -Class win32_VolumeChangeEvent -SourceIdentifier volumeChange
write-host (get-date -format s) " Beginning script..."
do {
$newEvent = Wait-Event -SourceIdentifier volumeChange
$eventType = $newEvent.SourceEventArgs.NewEvent.EventType
$eventTypeName = switch($eventType)
{
1 {"Configuration changed"}
2 {"Device arrival"}
3 {"Device removal"}
4 {"docking"}
}
write-host (get-date -format s) " Event detected = " $eventTypeName
$diskdrive = Get-WmiObject win32_diskdrive
if ($eventType -eq 2)
{ foreach($drive in $diskdrive)
{
out-host -InputObject "`nDevice: $($drive.deviceid.substring(4))`n Model: $($drive.model)"
$partitions = Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=`"$($drive.DeviceID.replace('\','\\'))`"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"
foreach($part in $partitions)
{
Out-Host -InputObject " Partition: $($part.name)"
$vols = Get-WmiObject -Query "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=`"$($part.DeviceID)`"} WHERE AssocClass = Win32_LogicalDiskToPartition"
foreach($vol in $vols)
{
out-host -InputObject " Volume: $($vol.name)"
$serial = Get-WmiObject -Class Win32_Volume | where { $_.Name -eq "$($vol.name)\" } | select SerialNumber
out-host -InputObject " Serial Number: $($serial.serialnumber)"
Write-EventLog -LogName Application -Source 'usb2.ps1' -EntryType Information -EventId '1' -Category 0 -Message "Date:$(get-date -format s) Event detected:$eventTypeName Serial:$($serial.serialnumber) Name:$($drive.model)"
}
}
}
}
if ($eventType -eq 3)
{
Write-EventLog -LogName Application -Source 'usb2.ps1' -EntryType Information -EventId '1' -Category 0 -Message "Event detected: $eventTypeName Serial:$($serial.serialnumber) Name:$($drive.model)"
}
Remove-Event -SourceIdentifier volumeChange
} while (1-eq1) #Loop until next event
Unregister-Event -SourceIdentifier volumeChange
答案 0 :(得分:0)
因为您调用命令:
$diskdrive = Get-WmiObject win32_diskdrive
此命令为您提供每个磁盘。
如果动作是"设备到达"你开始了#34;因为"显示有关磁盘的信息。
if ($eventType -eq 2)
{ foreach($drive in $diskdrive)
{ ... }}
在这" for"你需要控制磁盘是否是新的。因此,在启动程序之前,您必须知道哪个磁盘已插入。
此外,您可以使用WMI命令控制插入哪种类型的磁盘(对win_32不确定)。有一个选项可以给你一个数字来知道磁盘的类型(X代表硬盘,X代表USB等)。
抱歉我的英语很差,祝你好运:)