skjindal93
skjindal93

Reputation: 734

Auto Execute Script

I want to execute a script in Windows when a USB Device is plugged out or plugged in without any software. I need a script that would do that. I searched over internet but didn't find something helpful. Please help me.

Upvotes: 0

Views: 1097

Answers (2)

Shay Levy
Shay Levy

Reputation: 126722

You can subscribe to a WMI event:

$query = "SELECT * FROM __InstanceOperationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2"

Register-WmiEvent -Query $query -SourceIdentifier RemovableDiskDetection -Action {

    $class = $eventArgs.NewEvent.__CLASS
    $device = $eventArgs.NewEvent.TargetInstance.DeviceID

    switch($class)
    {
        __InstanceCreationEvent {
            Write-Host "Inserted, device id: $device"
        }

        __InstanceDeletionEvent {
            Write-Host "Removed, device id: $device"
        }
    }
}

Upvotes: 2

Bali C
Bali C

Reputation: 31221

You are looking for autorun.inf.

However, the functionality of automatically running scripts was disabled in Windows Vista and above to stop viruses spreading.

Upvotes: -1

Related Questions