Friday, April 22, 2016

Executing Powershell commands through TestComplete

Powershell is an extremely powerful toolbox and the ability to use it through TestComplete adds a whole new dimension to efficiently automating testing and related activities.

Here is a VBScript example of what you might do using TestComplete and Powershell.

Library function to execute Powershell command:

FUNCTION lib_run_pwsh_cmd(ByVal pre_cmd, ByVal psh_cmd)
  DIM wsh : SET wsh = CreateObject("WScript.shell")
  DIM launch_pshell : launch_pshell = "powershell.exe -noexit -ExecutionPolicy ByPass"
  DIM final_pshCommand : final_pshCommand = launch_pshell & " " & pre_cmd & ";" & psh_cmd & ";exit"
  Log.Message("PShell command : " & final_pshCommand)
  r = wsh.run(final_pshCommand,,true)
END FUNCTION


The launch_pshell command fires up the powershell command window with a -noexit flag which means the window will stay open after the execution is done. I choose to do that so in case something doesn't go right, I can see the output in the window to debug.

The pre_cmd is any powershell command that I need to execute before doing the actual operation. e.g. change directory to a particular location i.e. cd "C:\TC11Projects"

the psh_cmd is the actual powershell command/script that I want to execute. e.g. GenerateData.ps1 -data_descriptor "US_PHONE_NUMBERS"

This executes the script GenerateData.ps1 and passes the argument for the data_descriptor parameter.

The final_pshCommand shows what is called command chaining in command line execution which means it executes all the commands separated by ';' one after the other.

The 'exit' command in the end exits powershell.

Here is how I would call the above Function:

SUB TestPowershellFunction
DIM preCmd, pshCmd
preCmd = "cd C:\TC11Projects"
pshCmd = "GenerateData.ps1 -data_descriptor 'US_PHONE_NUMBERS'"
CALL lib_run_pwsh_cmd(preCmd,pshCmd)
END SUB