|PSH Oneliner: Detect If Running On Virtual Machine|
|Written by Darwin Sanoy|
|Thursday, December 11, 2014 9:35pm|
I had to create a script that was only supposed to run on a virtual machine. It needed to detect at least Hyper-V and VMWare, but I was about to get VirtualBox for free...
Here is the code
(gwmi win32_computersystem | select -expand model) -ilike "*virtual*"
Note the use if the "-ilike" operator. The -match operator can have some unintended consequences if you don't keep in mind that you are dealing with a regular express. -ilike is case independent and uses the very familiar "*" character as a wildcard.
You can modify the code to set a boolean variable like this:
$IsVirtual = [bool]((gwmi win32_computersystem | select -expand model) -ilike "*virtual*")
Or create a function like this:
Drop a line if you know of other hypervisors that contain "virtual" in their computer model!