19 June 2010

Enabling and disabling system hardware using vbscript in QTP

You can enable or disable any hardware component in your system using Vb-script. It is a simple and a very small code hardly few lines. All that you require is a small program called Devcon. It is a command line utility that lets you perform a few management functions on the system hardware. You need to download this program from Microsoft free of cost and extract the file "devcon.exe" anywhere in your computer. "devcon.exe" is available for both 32 bit and 64 bit machines and works for Windows 2000, Windows XP, Windows Server 2003, Windows Vista and Windows 7.

Now lets get to the scripting part, you need to execute the command line arguments using VB-Script. To achieve this, you will have to create an object of Windows Scripting Host (WSH) and use the execute method to fire the command line arguments.

In the example code below i have placed the "devcon.exe" in my drive C. To retrieve the hardware id you can rum the following code from the command prompt -

C:\>C:\devcon hwids * >> C:\myhwdids.txt

The above statement will create a text file listing all the hardware ids in your system in C:\myhwdids.txt.

The code for QTP -

hardwareID = "PCI\VEN_10EC&DEV_8168&SUBSYS_83851043&REV_01"
'Change with your hardware id

devconLocation = "C:\devcon.exe"
'Change with your devcon location

disableEnableHwd hardwareID, devconLocation, True
'Call the subroutine

'Subroutine disableEnableHwd Author Anunay
'If optHwdDecision is boolean True then hardware is enabled
'If optHwdDecision is boolean False then hardware is disabled
'devconLocation is the string location of the devcon.exe file in your system       
'hardwareID is the hardware id of the hardware component that you wish to disable 
Sub disableEnableHwd(hardwareID, devconLocation, optHwdDecision)
 If optHwdDecision Then
  hwdDecision = "enable "
  hwdDecision = "disable "
 End If
 Dim WshShell, oExec
 Set WshShell = CreateObject("WScript.Shell")
 Set oExec = WshShell.Exec("cmd /c " & devconLocation & " " & hwdDecision & hardwareID)
 Do While oExec.Status = 0
End Sub

1 comment:

  1. The DevCon Utility linked on this script is actually out of date and does not work properly in 64 bit environments w/non-itanium CPUs.

    You will need to get the latest version of the Windows Driver Kit in order to obtain the updated 7.x version of DevCon which will work correctly in 64-Bit Windows w/non-itanium CPUs.