Here is some code I got help to write for the AutoIt scripting language. I do not like to use it because I do not understand it. So if the code stopped working I would not know how to fix it. But this checks to see if the yubikey of a certain serial number is inserted or not. You check every second or two and if it is not inserted perform some action like locking the PC or something and when it is inserted go back into a loop of checking again.
Code:
Func CheckForYubikey($input)
$Output = ""
$object = ObjGet("winmgmts:\\" & $strComputer & "\ROOT\CIMV2")
$items = $object.ExecQuery("SELECT DeviceID FROM Win32_Keyboard", "WQL", _
$wbemFlagReturnImmediately + $wbemFlagForwardOnly)
If IsObj($items) Then
For $objItem In $items
If StringInStr($objItem.DeviceID, $YubikeySerialNumber) Then Return True
Next
Else
Return False
EndIf
Return False
EndFunc ;==>CheckForYubikey
EDIT, I should add this no longer works with my new Yubikey. It works for the old one but I think it no longer is a "keyboard" so this never sees the entry with my new serial number on it. Case in point, I am clueless as to how to tweak that code to make it work with what ever is the new "type" of device windows sees this as. But this is a proof of concept with the older v2.2.2 firmware devices. It worked flawlessly.