Hi,
Recently I posted an article on how to send key strokes and text to a Hyper-V virtual machine through use of WMI on the host computer. Since that article was written I’ve learned of a way to send any key combinations through to the VM. For example if you wanted to send the Alt+F4 key combination.
there is a method of the MSVM_Keyboard class called “TypeScanCodes” this method allows us to send key combinations to the Guest OS. Each key has a “Scan Code”, a list of which can be found here.
All we need to do is look up the decimal Scan Codes using the above lookup table, and we can send any key combination to the Hyper-V machine. For example to send the Alt+F4 key combination, we look up the decimal scan codes for the Left Alt key and the F4 Key using the above table. Left Alt = 56, F4 = 62.
We then create a byte array in PowerShell with the decimal scan codes we looked up:
1 |
$Codes = @([byte]56,[byte]62) |
Then we execute the method:
1 2 3 |
$ComputerSystem = Get-WmiObject -Query "select * from Msvm_ComputerSystem where ElementName = 'MY_VM_NAME'" -Namespace "root\virtualization\v2" $Keyboard = Get-WmiObject -Query "ASSOCIATORS OF {$($ComputerSystem.path.path)} WHERE resultClass = Msvm_Keyboard" -Namespace "root\virtualization\v2" $Keyboard.TypeScanCodes($Codes) |
Another example is sending the Escape key:
1 2 |
$Codes = @([byte]1) $Keyboard.TypeScanCodes($Codes) |
Alternatively you could skip creating the array and send the arguments all in one line like so:
1 2 |
$Keyboard.TypeScanCodes(@([byte]56,[byte]62)) $Keyboard.TypeScanCodes(@([byte]1)) |
Hi can this be used on the local machine, instead of VM. How would I change the coding for this? Would really appreciate your feedback