Customize the any object class operation with RegisterUserFunc with below steps.
1. Create one function with expected behavior code
2. Register same with below statement.
RegisterUserFunc TOClass, MethodName, FunctionName, SetAsDefault
Code Snippet:-
1. Define the Function
Function existEdit(Editbox, x)
If Editbox.exist(10) Then
Set objReference =Editbox
strClassName = objReference.GetTOProperty("attached text")
reporter.ReportEvent micDone, "Entered data in Edit box"," entered < " & x & "> value in " & strClassName
editbox.set x
End If
End Function
2. Register the function for Object class operation.
RegisterUserFunc "WinEdit", "set", "existEdit"
Use the Registered user function with below code :-
Dialog("Login").WinEdit("Agent Name:").Set "TestData "
For customize function unregister use below statement.
UnRegisterUserFunc "WinEdit", "Set"
Monday, January 3, 2011
Thursday, October 28, 2010
Command Prompt Automation
Automate CMD options with below code using WScript.Shell object.
1. Execute Commands in CMD with QTP code
with below code execute command in CMD with single step using below code:-
Set app=CreateObject("Wscript.shell")
SystemUtil.run("cmd.exe")
app.Run "CMD /k cd\ & c:\CreateCamp_Sample.xls"
with below code execute CMD commands step by step:-
Set app=CreateObject("Wscript.shell")
SystemUtil.run("cmd.exe")
app.sendkeys "cd\"
app.sendkeys "~" 'It is for enter key
app.sendkeys "c:"
app.sendkeys "~"
app.sendkeys "CreateCamp_Sample.xls"
app.sendkeys "~"
2. Get displayed text from Command prompt'
with below code ping in command propmt and capture the output :-
'Create WScript Shell object
Set oWshShell = CreateObject("wscript.Shell")
'' We'll execute the ping command
sCmd = "ping google.com"
'' Execute the command
Set oExec = oWshShell.Exec(sCmd)
'' Loop untill the command has completed.
Do While oExec.Status = 0
wait 1
Loop
'' Show the console output
sStdout = oExec.StdOut.ReadAll
sStdErr = oExec.StdErr.ReadAll
MsgBox "stdout: " & sStdout & vbNewLine & vbNewLine & "stderr: " & sStderr
3.script to get the information of the mapped network drives
Option Explicit
Dim oNet, oDrives
Dim i
''--- Adding to new entries to datatable
DataTable.LocalSheet.AddParameter "Drive", vbNullString
DataTable.LocalSheet.AddParameter "Value", vbNullString
'
''--- Creating a WshNetwork object
Set oNet = CreateObject("WScript.Network")
Set oDrives = oNet.EnumNetworkDrives
For i = 0 to oDrives.Count - 1 Step 2
DataTable.LocalSheet.SetCurrentRow i + 1
DataTable("Drive", dtLocalSheet) = oDrives.Item(i)
DataTable("Value", dtLocalSheet) = oDrives.Item(i + 1)
Next
Set oDrives = Nothing
Set oNet = Nothing
4. script to Copy the Files from local machine to Remote system
Copy and past the files from local machine to Remote machine with below function. This works for Copy and past files from Quality centre / QC to Remote machine.
fnCopyFilesFromNetworkDrive
Function fnCopyFilesFromNetworkDrive
Dim ServerShare, UserName, Password, strQcPathTestdataDirectory
Dim NetworkObject, FSO, strDirectory, objFile
'ServerShare = "\\perfcompare.eprintlab.ipgrndhub.in"
If trim(Datatable.Value("RemoteSystemAddress","Global") )= ""Then
Print "RemoteSystemAddress Column does not have value, so exit from run"
Reporter.ReportEvent micWarning," datatable column value is empty"," datatable column value is empty, so exited from execution"
exitAction "FAIL"
End If
ServerShare ="\\"& Datatable.Value("RemoteSystemAddress","Global") ' "\\xxx.xxx.x.xxx"
If Trim(Datatable.value("RemoteSysLoginUName","Global"))="" Then
UserName = "Domain\Username"
End If
If Trim(Datatable.Value("RemoteSysLoginPassword","Global"))="" Then
Password = "password"
End If
Set NetworkObject = CreateObject("WScript.Network")
Set FSO = CreateObject("Scripting.FileSystemObject")
Reporter.ReportEvent micDone,"Network system Address " & ServerShare,ServerShare &" network system accessed with " & UserName & " as Username and " & Password &" as password"
NetworkObject.MapNetworkDrive "", ServerShare, False, UserName, Password
Set strDirectory = FSO.GetFolder(ServerShare & "\c$\Folderpath\")
strQcPathTestdataDirectory="[QualityCenter] Subject\TestData\"
strQCTestData =strQcPathTestdataDirectory & Trim( Datatable.Value("QC_TestDataFileName","Global"))
strPath = PathFinder.Locate(strQCTestData)
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.copyFile strPath, strDirectory + "\" & Trim( Datatable.Value("QC_TestDataFileName","Global")) '
NetworkObject.RemoveNetworkDrive ServerShare, True, False
Set NetworkObject = Nothing
End Function
5. Get the List of Printers
Option Explicit
Dim oNet, oPrinters
Dim i
''--- Adding to new entries to datatable
DataTable.LocalSheet.AddParameter "Port", vbNullString
DataTable.LocalSheet.AddParameter "Value", vbNullString
''--- Creating a WshNetwork object
Set oNet = CreateObject("WScript.Network")
Set oPrinters = oNet.EnumPrinterConnections
For i = 0 to oPrinters.Count - 1 Step 2
DataTable.LocalSheet.SetCurrentRow i + 1
DataTable("Port", dtLocalSheet) = oPrinters.Item(i)
DataTable("Value", dtLocalSheet) = oPrinters.Item(i + 1)
Next
6. Create registry key , modify and delete same
''Script to add,delete and modify registry
Dim sDefault, sBinary, sString, sDWord, sExpand
''--- Creating a shell object
Set oShell = CreateObject("WScript.Shell")
''--- Creating registry values
oShell.RegWrite "HKCU\Software\QTP\", "Default Key", "REG_SZ"
oShell.RegWrite "HKCU\Software\QTP\Binary", 180150008, "REG_BINARY"
oShell.RegWrite "HKCU\Software\QTP\String", "String", "REG_SZ"
oShell.RegWrite "HKCU\Software\QTP\DWord", &HABCDEF8, "REG_DWORD"
oShell.RegWrite "HKCU\Software\QTP\ExpandedString", "%SystemRoot%", "REG_EXPAND_SZ"
''--- Reading registry values
sDefault = oShell.RegRead("HKCU\Software\QTP\")
sBinary = oShell.RegRead("HKCU\Software\QTP\Binary")
sString = oShell.RegRead("HKCU\Software\QTP\String")
sDWord = oShell.RegRead("HKCU\Software\QTP\DWord")
sExpand = oShell.RegRead("HKCU\Software\QTP\ExpandedString")
''--- Deleting a key value
oShell.RegDelete "HKCU\Software\QTP\String"
''--- Deleting a whole key
oShell.RegDelete "HKCU\Software\QTP\String"
7. script for logging events to event log
The LogEvent method returns a Boolean value (true if the event is logged
successfully, otherwise false). In Windows NT/2000, events are logged in
the Windows NT Event Log.
In Windows 9x/Me, events are logged in WSH.log (located in the Windows
directory). There are six event types.
Option Explicit
''--- Declaring Event types constants
Private Const LOG_SUCCESS = 0
Private Const LOG_ERROR = 1
Private Const LOG_WARNING = 2
Private Const LOG_INFORMATION = 4
Private Const LOG_AUDIT_SUCCESS = 8
Private Const LOG_AUDIT_FAILURE = 16
Dim oShell
''--- Creating a shell object
Set oShell = CreateObject("WScript.Shell")
oShell.LogEvent LOG_SUCCESS, "Logon Script Success."
oShell.LogEvent LOG_ERROR, "Logon Script Error."
oShell.LogEvent LOG_WARNING, "Logon Script Warning."
oShell.LogEvent LOG_INFORMATION, "Logon Script Information."
oShell.LogEvent LOG_AUDIT_SUCCESS, "Logon Script Audit Success."
oShell.LogEvent LOG_AUDIT_FAILURE, "Logon Script Audit Failure."
''--- Cleaning used objects
Set oShell = Nothing
8. script to create shortcut for QTP
Option Explicit
Dim oShell, oShLink
Dim sPath, sDesktop
Dim oFso
Set oFso = CreateObject("Scripting.FileSystemObject")
''--- Creating a WshShell object
Set oShell = CreateObject("WScript.Shell")
''--- Retrive the user desktop location
sDeskTop = oShell.SpecialFolders.Item("Desktop")
sPath = oFso.BuildPath(sDesktop, "Shortcut to QuickTest.lnk")
''--- Create a WshShortcut object
Set oShLink = oShell.CreateShortcut(sPath)
sPath = oFso.BuildPath(Environment("ProductDir"), "bin\QTPro.exe")
oShLink.TargetPath = sPath
oShLink.WindowStyle = 1
oShLink.Hotkey = "CTRL+SHIFT+Q"
sPath = oFso.BuildPath(Environment("ProductDir"), "bin\QTPro.exe")
oShLink.IconLocation = sPath & ", 0"
oShLink.Description = "Activates QuickTest Professional Testing Tool"
oShLink.WorkingDirectory= oFso.BuildPath(Environment("ProductDir"), "bin\")
oShLink.Save
Set oShell = Nothing
Set oFso = Nothing
Set oShLink = Nothing
9. scirpt to retreive windows environmnet variables
Option Explicit
Dim oShell, oEnvProc, oEnvSys, oItem
Dim arrEnv
Dim nRow : nRow = 1
''--- Creating 2 new columns in local sheet
DataTable.LocalSheet.AddParameter "Type", vbNullString
DataTable.LocalSheet.AddParameter "Variable", vbNullString
DataTable.LocalSheet.AddParameter "Value", vbNullString
''--- Creating a WshShell object
Set oShell = CreateObject("WScript.Shell")
''--- Retrieve the System environments collection
Set oEnvSys = oShell.Environment("System")
''--- Retrieve the Process/User environments collection
Set oEnvProc = oShell.Environment("Process")
Reporter.ReportEvent micDone, "Sys Count", oEnvSys.Count
Reporter.ReportEvent micDone, "Proc Count", oEnvProc.Count
''--- Retrieve System env. variables
For Each oItem In oEnvSys
DataTable.LocalSheet.SetCurrentRow nRow
nRow = nRow + 1
arrEnv = Split(oItem, "=")
DataTable("Type", dtLocalSheet) = "System"
DataTable("Variable", dtLocalSheet) = arrEnv(0)
DataTable("Value", dtLocalSheet) = arrEnv(1)
Erase arrEnv
Next
'--- Retrieve System env. variables
For Each oItem In oEnvProc
DataTable.LocalSheet.SetCurrentRow nRow
nRow = nRow + 1
arrEnv = Split(oItem, "=")
DataTable("Type", dtLocalSheet) = "Process"
DataTable("Variable", dtLocalSheet) = arrEnv(0)
DataTable("Value", dtLocalSheet) = arrEnv(1)
Erase arrEnv
Next
Set oShell = Nothing
Set oEnvProc = Nothing
Set oEnvSys = Nothing
10. Script to start the windows service in remote system or VM Using WMI
'Call the Function for start the Service in Remote system or VM with QTP Script
StartService "Computer Name","Service Name",True/False
Function StartService(Computer, ServiceName, blnWait)
strUser = "remote computer user name" ' Domain name\ username
strPassword ="give the password here"
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
If Not(IsNull(objLocator)) Then
Set cimv2 = objLocator.ConnectServer(Computer, "root/cimv2", strUser, strPassword)
Print "Computer Name: " & Computer
If Not(IsNull(cimv2)) Then
Set oServices = cimv2.InstancesOf("Win32_Service")
If (Not(IsNull(oServices))) Then
For each oService in oServices
If StrComp(oService.Name, ServiceName) = 0 Then
Print "Service Found"
Exit For
End If
Print "Service Name: " & oService.Name
Next
End If
End If
End If
'Check base properties
If oService.Started Then
' the service is Not started
Print "The service " & ServiceName & " is started."
exit Sub
End If
'Start the service
Result = oService.StartService
If 0 <> Result Then
Print "Start " & ServiceName & " error:" & Result
exit Sub
End If
Do While InStr(1,oService.State,"running",1) = 0 And blnWait
'get the current service state
Set oService = cimv2.Get("Win32_Service.Name='" & ServiceName & "'")
Print "StartService" &" - - ServiceName - - "& ServiceName &" - - oService.Started - -"& oService.Started &" - - oService.State - - "& oService.State &"-- oService.Status - - "& oService.Status
Wait (2)
Loop
End Function
11. Script to Stop the windows service in remote system or VM Using WMI
' Call the function for stop the service in remote system or VM with QTP
StopService "Compute name","Service Name" True / False
Function StopService(Computer, ServiceName, blnWait)
Dim cimv2, oService, Result, strUser, strPassword
strUser = "DomainName\Administrator"
strPassword = "password" 'give the password here
Set objLocator = CreateObject( "WbemScripting.SWbemLocator" )
If Not(IsNull(objLocator)) Then
Set cimv2 = objLocator.ConnectServer(Computer, "root/cimv2", strUser, strPassword )
Print "Computer Name: " & Computer
If Not(IsNull(cimv2)) Then
Set oServices = cimv2.InstancesOf("Win32_Service")
If (Not(IsNull(oServices))) Then
For each oService in oServices
If StrComp(oService.Name, ServiceName) = 0 Then
Print "Service Found"
Exit For
End If
Print "Service Name: " & oService.Name
Next
End If
End If
End If
'Check base properties
If Not oService.Started Then
' the service is Not started
Print "The service " & ServiceName & " is Not started"
exit Sub
End If
oService.StartService()
If Not oService.AcceptStop Then
' the service does Not accept stop command
Print "The service " & ServiceName & " does Not accept stop command"
exit Sub
End If
'Stop the service
Result = oService.StopService
If 0 <> Result Then
If Result = 3 Then
'Need to stop the dependent services
Set oDepServices = cimv2.ExecQuery( "Associators of {Win32_Service.Name='" & oService.Name & "'} Where AssocClass=Win32_DependentService Role=Antecedent")
If (Not(IsNull(oDepServices))) Then
For Each objService in oDepServices
Print "Dependent service: " & objService.Name & " State: " & objService.State
Print "Stopping dependent service " & objService.Name
objService.StopService()
Next
End If
End If
Wait (2)
Print "Stopping" & oService.Name & "service"
Result = oService.StopService()
If 0 <> Result Then
Print "Stop " & ServiceName & " error: " & Result
exit Sub
End If
End If
Do While oService.Started And blnWait
'get the current service state
Set oService = cimv2.Get("Win32_Service.Name='" & ServiceName & "'")
Print "StopService" &"ServiceName - - "& ServiceName &"oService.Started - - "& oService.Started &" oService.State - - "& oService.State &" oService.Status - - "& oService.Status
' Print now, "StopService", ServiceName, oService.Started, oService.State, oService.Status
Wait (2)
Loop
End function
.
1. Execute Commands in CMD with QTP code
with below code execute command in CMD with single step using below code:-
Set app=CreateObject("Wscript.shell")
SystemUtil.run("cmd.exe")
app.Run "CMD /k cd\ & c:\CreateCamp_Sample.xls"
with below code execute CMD commands step by step:-
Set app=CreateObject("Wscript.shell")
SystemUtil.run("cmd.exe")
app.sendkeys "cd\"
app.sendkeys "~" 'It is for enter key
app.sendkeys "c:"
app.sendkeys "~"
app.sendkeys "CreateCamp_Sample.xls"
app.sendkeys "~"
2. Get displayed text from Command prompt'
with below code ping in command propmt and capture the output :-
'Create WScript Shell object
Set oWshShell = CreateObject("wscript.Shell")
'' We'll execute the ping command
sCmd = "ping google.com"
'' Execute the command
Set oExec = oWshShell.Exec(sCmd)
'' Loop untill the command has completed.
Do While oExec.Status = 0
wait 1
Loop
'' Show the console output
sStdout = oExec.StdOut.ReadAll
sStdErr = oExec.StdErr.ReadAll
MsgBox "stdout: " & sStdout & vbNewLine & vbNewLine & "stderr: " & sStderr
3.script to get the information of the mapped network drives
Option Explicit
Dim oNet, oDrives
Dim i
''--- Adding to new entries to datatable
DataTable.LocalSheet.AddParameter "Drive", vbNullString
DataTable.LocalSheet.AddParameter "Value", vbNullString
'
''--- Creating a WshNetwork object
Set oNet = CreateObject("WScript.Network")
Set oDrives = oNet.EnumNetworkDrives
For i = 0 to oDrives.Count - 1 Step 2
DataTable.LocalSheet.SetCurrentRow i + 1
DataTable("Drive", dtLocalSheet) = oDrives.Item(i)
DataTable("Value", dtLocalSheet) = oDrives.Item(i + 1)
Next
Set oDrives = Nothing
Set oNet = Nothing
4. script to Copy the Files from local machine to Remote system
Copy and past the files from local machine to Remote machine with below function. This works for Copy and past files from Quality centre / QC to Remote machine.
fnCopyFilesFromNetworkDrive
Function fnCopyFilesFromNetworkDrive
Dim ServerShare, UserName, Password, strQcPathTestdataDirectory
Dim NetworkObject, FSO, strDirectory, objFile
'ServerShare = "\\perfcompare.eprintlab.ipgrndhub.in"
If trim(Datatable.Value("RemoteSystemAddress","Global") )= ""Then
Print "RemoteSystemAddress Column does not have value, so exit from run"
Reporter.ReportEvent micWarning,"
exitAction "FAIL"
End If
ServerShare ="\\"& Datatable.Value("RemoteSystemAddress","Global") ' "\\xxx.xxx.x.xxx"
If Trim(Datatable.value("RemoteSysLoginUName","Global"))="" Then
UserName = "Domain\Username"
End If
If Trim(Datatable.Value("RemoteSysLoginPassword","Global"))="" Then
Password = "password"
End If
Set NetworkObject = CreateObject("WScript.Network")
Set FSO = CreateObject("Scripting.FileSystemObject")
Reporter.ReportEvent micDone,"Network system Address " & ServerShare,ServerShare &" network system accessed with " & UserName & " as Username and " & Password &" as password"
NetworkObject.MapNetworkDrive "", ServerShare, False, UserName, Password
Set strDirectory = FSO.GetFolder(ServerShare & "\c$\Folderpath\")
strQcPathTestdataDirectory="[QualityCenter] Subject\TestData\"
strQCTestData =strQcPathTestdataDirectory & Trim( Datatable.Value("QC_TestDataFileName","Global"))
strPath = PathFinder.Locate(strQCTestData)
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.copyFile strPath, strDirectory + "\" & Trim( Datatable.Value("QC_TestDataFileName","Global")) '
NetworkObject.RemoveNetworkDrive ServerShare, True, False
Set NetworkObject = Nothing
End Function
5. Get the List of Printers
Option Explicit
Dim oNet, oPrinters
Dim i
''--- Adding to new entries to datatable
DataTable.LocalSheet.AddParameter "Port", vbNullString
DataTable.LocalSheet.AddParameter "Value", vbNullString
''--- Creating a WshNetwork object
Set oNet = CreateObject("WScript.Network")
Set oPrinters = oNet.EnumPrinterConnections
For i = 0 to oPrinters.Count - 1 Step 2
DataTable.LocalSheet.SetCurrentRow i + 1
DataTable("Port", dtLocalSheet) = oPrinters.Item(i)
DataTable("Value", dtLocalSheet) = oPrinters.Item(i + 1)
Next
6. Create registry key , modify and delete same
''Script to add,delete and modify registry
Dim sDefault, sBinary, sString, sDWord, sExpand
''--- Creating a shell object
Set oShell = CreateObject("WScript.Shell")
''--- Creating registry values
oShell.RegWrite "HKCU\Software\QTP\", "Default Key", "REG_SZ"
oShell.RegWrite "HKCU\Software\QTP\Binary", 180150008, "REG_BINARY"
oShell.RegWrite "HKCU\Software\QTP\String", "String", "REG_SZ"
oShell.RegWrite "HKCU\Software\QTP\DWord", &HABCDEF8, "REG_DWORD"
oShell.RegWrite "HKCU\Software\QTP\ExpandedString", "%SystemRoot%", "REG_EXPAND_SZ"
''--- Reading registry values
sDefault = oShell.RegRead("HKCU\Software\QTP\")
sBinary = oShell.RegRead("HKCU\Software\QTP\Binary")
sString = oShell.RegRead("HKCU\Software\QTP\String")
sDWord = oShell.RegRead("HKCU\Software\QTP\DWord")
sExpand = oShell.RegRead("HKCU\Software\QTP\ExpandedString")
''--- Deleting a key value
oShell.RegDelete "HKCU\Software\QTP\String"
''--- Deleting a whole key
oShell.RegDelete "HKCU\Software\QTP\String"
7. script for logging events to event log
The LogEvent method returns a Boolean value (true if the event is logged
successfully, otherwise false). In Windows NT/2000, events are logged in
the Windows NT Event Log.
In Windows 9x/Me, events are logged in WSH.log (located in the Windows
directory). There are six event types.
Option Explicit
''--- Declaring Event types constants
Private Const LOG_SUCCESS = 0
Private Const LOG_ERROR = 1
Private Const LOG_WARNING = 2
Private Const LOG_INFORMATION = 4
Private Const LOG_AUDIT_SUCCESS = 8
Private Const LOG_AUDIT_FAILURE = 16
Dim oShell
''--- Creating a shell object
Set oShell = CreateObject("WScript.Shell")
oShell.LogEvent LOG_SUCCESS, "Logon Script Success."
oShell.LogEvent LOG_ERROR, "Logon Script Error."
oShell.LogEvent LOG_WARNING, "Logon Script Warning."
oShell.LogEvent LOG_INFORMATION, "Logon Script Information."
oShell.LogEvent LOG_AUDIT_SUCCESS, "Logon Script Audit Success."
oShell.LogEvent LOG_AUDIT_FAILURE, "Logon Script Audit Failure."
''--- Cleaning used objects
Set oShell = Nothing
8. script to create shortcut for QTP
Option Explicit
Dim oShell, oShLink
Dim sPath, sDesktop
Dim oFso
Set oFso = CreateObject("Scripting.FileSystemObject")
''--- Creating a WshShell object
Set oShell = CreateObject("WScript.Shell")
''--- Retrive the user desktop location
sDeskTop = oShell.SpecialFolders.Item("Desktop")
sPath = oFso.BuildPath(sDesktop, "Shortcut to QuickTest.lnk")
''--- Create a WshShortcut object
Set oShLink = oShell.CreateShortcut(sPath)
sPath = oFso.BuildPath(Environment("ProductDir"), "bin\QTPro.exe")
oShLink.TargetPath = sPath
oShLink.WindowStyle = 1
oShLink.Hotkey = "CTRL+SHIFT+Q"
sPath = oFso.BuildPath(Environment("ProductDir"), "bin\QTPro.exe")
oShLink.IconLocation = sPath & ", 0"
oShLink.Description = "Activates QuickTest Professional Testing Tool"
oShLink.WorkingDirectory= oFso.BuildPath(Environment("ProductDir"), "bin\")
oShLink.Save
Set oShell = Nothing
Set oFso = Nothing
Set oShLink = Nothing
9. scirpt to retreive windows environmnet variables
Option Explicit
Dim oShell, oEnvProc, oEnvSys, oItem
Dim arrEnv
Dim nRow : nRow = 1
''--- Creating 2 new columns in local sheet
DataTable.LocalSheet.AddParameter "Type", vbNullString
DataTable.LocalSheet.AddParameter "Variable", vbNullString
DataTable.LocalSheet.AddParameter "Value", vbNullString
''--- Creating a WshShell object
Set oShell = CreateObject("WScript.Shell")
''--- Retrieve the System environments collection
Set oEnvSys = oShell.Environment("System")
''--- Retrieve the Process/User environments collection
Set oEnvProc = oShell.Environment("Process")
Reporter.ReportEvent micDone, "Sys Count", oEnvSys.Count
Reporter.ReportEvent micDone, "Proc Count", oEnvProc.Count
''--- Retrieve System env. variables
For Each oItem In oEnvSys
DataTable.LocalSheet.SetCurrentRow nRow
nRow = nRow + 1
arrEnv = Split(oItem, "=")
DataTable("Type", dtLocalSheet) = "System"
DataTable("Variable", dtLocalSheet) = arrEnv(0)
DataTable("Value", dtLocalSheet) = arrEnv(1)
Erase arrEnv
Next
'--- Retrieve System env. variables
For Each oItem In oEnvProc
DataTable.LocalSheet.SetCurrentRow nRow
nRow = nRow + 1
arrEnv = Split(oItem, "=")
DataTable("Type", dtLocalSheet) = "Process"
DataTable("Variable", dtLocalSheet) = arrEnv(0)
DataTable("Value", dtLocalSheet) = arrEnv(1)
Erase arrEnv
Next
Set oShell = Nothing
Set oEnvProc = Nothing
Set oEnvSys = Nothing
10. Script to start the windows service in remote system or VM Using WMI
'Call the Function for start the Service in Remote system or VM with QTP Script
StartService "Computer Name","Service Name",True/False
Function StartService(Computer, ServiceName, blnWait)
strUser = "remote computer user name" ' Domain name\ username
strPassword ="give the password here"
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
If Not(IsNull(objLocator)) Then
Set cimv2 = objLocator.ConnectServer(Computer, "root/cimv2", strUser, strPassword)
Print "Computer Name: " & Computer
If Not(IsNull(cimv2)) Then
Set oServices = cimv2.InstancesOf("Win32_Service")
If (Not(IsNull(oServices))) Then
For each oService in oServices
If StrComp(oService.Name, ServiceName) = 0 Then
Print "Service Found"
Exit For
End If
Print "Service Name: " & oService.Name
Next
End If
End If
End If
'Check base properties
If oService.Started Then
' the service is Not started
Print "The service " & ServiceName & " is started."
exit Sub
End If
'Start the service
Result = oService.StartService
If 0 <> Result Then
Print "Start " & ServiceName & " error:" & Result
exit Sub
End If
Do While InStr(1,oService.State,"running",1) = 0 And blnWait
'get the current service state
Set oService = cimv2.Get("Win32_Service.Name='" & ServiceName & "'")
Print "StartService" &" - - ServiceName - - "& ServiceName &" - - oService.Started - -"& oService.Started &" - - oService.State - - "& oService.State &"-- oService.Status - - "& oService.Status
Wait (2)
Loop
End Function
11. Script to Stop the windows service in remote system or VM Using WMI
' Call the function for stop the service in remote system or VM with QTP
StopService "Compute name","Service Name" True / False
Function StopService(Computer, ServiceName, blnWait)
Dim cimv2, oService, Result, strUser, strPassword
strUser = "DomainName\Administrator"
strPassword = "password" 'give the password here
Set objLocator = CreateObject( "WbemScripting.SWbemLocator" )
If Not(IsNull(objLocator)) Then
Set cimv2 = objLocator.ConnectServer(Computer, "root/cimv2", strUser, strPassword )
Print "Computer Name: " & Computer
If Not(IsNull(cimv2)) Then
Set oServices = cimv2.InstancesOf("Win32_Service")
If (Not(IsNull(oServices))) Then
For each oService in oServices
If StrComp(oService.Name, ServiceName) = 0 Then
Print "Service Found"
Exit For
End If
Print "Service Name: " & oService.Name
Next
End If
End If
End If
'Check base properties
If Not oService.Started Then
' the service is Not started
Print "The service " & ServiceName & " is Not started"
exit Sub
End If
oService.StartService()
If Not oService.AcceptStop Then
' the service does Not accept stop command
Print "The service " & ServiceName & " does Not accept stop command"
exit Sub
End If
'Stop the service
Result = oService.StopService
If 0 <> Result Then
If Result = 3 Then
'Need to stop the dependent services
Set oDepServices = cimv2.ExecQuery( "Associators of {Win32_Service.Name='" & oService.Name & "'} Where AssocClass=Win32_DependentService Role=Antecedent")
If (Not(IsNull(oDepServices))) Then
For Each objService in oDepServices
Print "Dependent service: " & objService.Name & " State: " & objService.State
Print "Stopping dependent service " & objService.Name
objService.StopService()
Next
End If
End If
Wait (2)
Print "Stopping" & oService.Name & "service"
Result = oService.StopService()
If 0 <> Result Then
Print "Stop " & ServiceName & " error: " & Result
exit Sub
End If
End If
Do While oService.Started And blnWait
'get the current service state
Set oService = cimv2.Get("Win32_Service.Name='" & ServiceName & "'")
Print "StopService" &"ServiceName - - "& ServiceName &"oService.Started - - "& oService.Started &" oService.State - - "& oService.State &" oService.Status - - "& oService.Status
' Print now, "StopService", ServiceName, oService.Started, oService.State, oService.Status
Wait (2)
Loop
End function
.
Labels:
Command Prompt Automation
Friday, October 15, 2010
Get the Node Name and Node value from XML file
Use below code and get each node name and value of XML file.
Read all the nodes and their values in the xml file:-
Set xmlobj=createobject("Msxml2.DOMDocument.3.0")
xmlobj.load "C:\ FileName.xml"
set ndRoot=xmlobj.documentElement
'msgbox ndRoot.nodeName
Set ndChilds=ndRoot.childNodes
intRow=1
For i=2 to ndChilds.length-1
set ndChild=ndChilds.item(i) 'general
Call fnChildNodes(ndChild)
Next
'Function that reads the node name and node value of a node including all its child nodes.
Function fnChildNodes(ndChild)
If ndChild.childNodes.length>0 then
datatable.SetCurrentRow(intRow)
datatable("NodeName",1)=ndChild.nodeName
set ndGrdChilds=ndChild.childNodes
If ndGrdChilds.item(0).nodeName="#text" Then
datatable("NodeValue",1)=ndChild.text
End If
intRow=intRow+1
set ndGrdChilds=ndChild.childNodes
If ndGrdChilds.item(0).nodeName<>"#text" Then
For j=0 to ndGrdChilds.length-1
set ndGrdChild=ndGrdChilds.item(j)
Call fnChildNodes(ndGrdChild)
Next
End IF
else
datatable.SetCurrentRow(intRow)
datatable("NodeName",1)=ndChild.nodeName
intRow=intRow+1
End If
End Function
Read all the nodes and their values in the xml file:-
Set xmlobj=createobject("Msxml2.DOMDocument.3.0")
xmlobj.load "C:\ FileName.xml"
set ndRoot=xmlobj.documentElement
'msgbox ndRoot.nodeName
Set ndChilds=ndRoot.childNodes
intRow=1
For i=2 to ndChilds.length-1
set ndChild=ndChilds.item(i) 'general
Call fnChildNodes(ndChild)
Next
'Function that reads the node name and node value of a node including all its child nodes.
Function fnChildNodes(ndChild)
If ndChild.childNodes.length>0 then
datatable.SetCurrentRow(intRow)
datatable("NodeName",1)=ndChild.nodeName
set ndGrdChilds=ndChild.childNodes
If ndGrdChilds.item(0).nodeName="#text" Then
datatable("NodeValue",1)=ndChild.text
End If
intRow=intRow+1
set ndGrdChilds=ndChild.childNodes
If ndGrdChilds.item(0).nodeName<>"#text" Then
For j=0 to ndGrdChilds.length-1
set ndGrdChild=ndGrdChilds.item(j)
Call fnChildNodes(ndGrdChild)
Next
End IF
else
datatable.SetCurrentRow(intRow)
datatable("NodeName",1)=ndChild.nodeName
intRow=intRow+1
End If
End Function
Labels:
XML Automation
Find the XML Node path based on node name
We can find Xpath for given node in XML file using with below two functions.
First function:--
Call ExtractProductCode
Function ExtractProductCode
Environment.Value("columnExcel")=3
Set doc = XMLUtil.CreateXML()
doc.LoadFile "C:\FileName.xml"
Set root = doc.GetRootElement
Environment.Value("ParentName") = root.ElementName()
'Set children = root.ChildElements()
'Msgbox children.Count()
call XMLDataExtract1(root.ChildElements(), root.ChildElements().Count())
End Function
Function XMLDataExtract1(children, cnt)
c1= children.Count()
If cnt > 0 Then
For i= 1 to cnt 'children.Count()
Set firstChild = children.Item(i)
c2 = firstChild.ElementName()
c3 = firstChild.Value()
If Trim(CStr(c2)) = Trim(DataTable.Value("NodeName","Global")) Then '
XMLPath= ""
While firstChild.ElementName() <>"soapenv:Envelope"
XMLPath= "/" & CStr(firstChild.ElementName()) & XMLPath
Set firstChild= firstChild.Parent()
Wend
XMLPath = "/" & Environment.Value("ParentName") & XMLPath
DataTable.Value(cInt(Environment.Value("columnExcel")),"Global") = XMLPath
Environment.Value("columnExcel")= cInt(Environment.Value("columnExcel"))+1
Exit Function
End If
If firstChild.ChildElements().Count() > 0 Then
Set children = firstChild.ChildElements()
call XMLDataExtract1(children,children.Count())
End if
Next
End If
Reporter.Filter = 3
'MsgBox firstChild.Parent().Parent().ElementName()
On Error Resume Next
Set children = firstChild.Parent().Parent().ChildElements()
On Error Goto 0
Reporter.Filter = 0
End Function
First function:--
Call ExtractProductCode
Function ExtractProductCode
Environment.Value("columnExcel")=3
Set doc = XMLUtil.CreateXML()
doc.LoadFile "C:\FileName.xml"
Set root = doc.GetRootElement
Environment.Value("ParentName") = root.ElementName()
'Set children = root.ChildElements()
'Msgbox children.Count()
call XMLDataExtract1(root.ChildElements(), root.ChildElements().Count())
End Function
Function XMLDataExtract1(children, cnt)
c1= children.Count()
If cnt > 0 Then
For i= 1 to cnt 'children.Count()
Set firstChild = children.Item(i)
c2 = firstChild.ElementName()
c3 = firstChild.Value()
If Trim(CStr(c2)) = Trim(DataTable.Value("NodeName","Global")) Then '
XMLPath= ""
While firstChild.ElementName() <>"soapenv:Envelope"
XMLPath= "/" & CStr(firstChild.ElementName()) & XMLPath
Set firstChild= firstChild.Parent()
Wend
XMLPath = "/" & Environment.Value("ParentName") & XMLPath
DataTable.Value(cInt(Environment.Value("columnExcel")),"Global") = XMLPath
Environment.Value("columnExcel")= cInt(Environment.Value("columnExcel"))+1
Exit Function
End If
If firstChild.ChildElements().Count() > 0 Then
Set children = firstChild.ChildElements()
call XMLDataExtract1(children,children.Count())
End if
Next
End If
Reporter.Filter = 3
'MsgBox firstChild.Parent().Parent().ElementName()
On Error Resume Next
Set children = firstChild.Parent().Parent().ChildElements()
On Error Goto 0
Reporter.Filter = 0
End Function
Labels:
XML Automation
Friday, June 25, 2010
How to Use Dictionary Object in QTP?
Simple Code example for Dictionary object:-
Dim objDict 'Create a variable
Set objDict = CreateObject("Scripting.Dictionary")
objDict.Add "Name", "SP" 'Add some keys and items
objDict.Add "Address", "Street1"
objDict.Add "City", "Bangalore"
objDict.Add "State","Karnataka"
objDict.Add "Country","India"
For Each I in objDict
msgbox objDict.Item(I)
Next
Please find the infromation in the below.
http://www.learnqtp.com/dictionary-object-qtp-use/
Dim objDict 'Create a variable
Set objDict = CreateObject("Scripting.Dictionary")
objDict.Add "Name", "SP" 'Add some keys and items
objDict.Add "Address", "Street1"
objDict.Add "City", "Bangalore"
objDict.Add "State","Karnataka"
objDict.Add "Country","India"
For Each I in objDict
msgbox objDict.Item(I)
Next
Please find the infromation in the below.
http://www.learnqtp.com/dictionary-object-qtp-use/
Labels:
General
Subscribe to:
Posts (Atom)