I'm new to PHPUnit. I'm developing on an existing system, adding new features. I want to use PHPUnit to test codes I made. However, the system runs only on server (CGI) environment (access from a browser), and everything breaks while running from command-line.
Is it possible to setting PHPUnit to make a test suite which can be invoked from web browser?
Personally, I'm using windows task manager (cron can do the same thing on linux) to generate my unit test and send it to a text file every night.
Instead of display it directly in the web browser like I do, you could parse the result file directly on your server and then send the html output by email. So you could simply examine the result page on your local machine every morning like I do. Here's some code to start up your solution (on windows/PHP).
In task manager:
Action 1: C:\xampp\htdocs\PC_administration_interface\Controler\Script\launch_automatic_test.bat
Action 2: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Argument action 2: http://localhost/PC_administration_interface/view/unit_test.php?DISPLAY_RESULT=TRUE
Launch_automatic_test.bat
#echo off
call %~DP0\launch_xampp.bat
call %~DP0\..\..\..\..\xampp_shell.bat
cls
call %~DP0\run_unit_test.bat > "%~DP0\..\test_result.txt"
launch_xampp_bat
#echo off
tasklist | find /i "xampp-control.exe" && goto :eof
start /b "xampp-control.exe" "C:\xampp\xampp-control.exe"
And here's a sample of run_unit_tets.bat
#ECHO OFF
CLS
REM GEM_MECHANIC_TESTS
ECHO.
ECHO FILE : GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GEM_MECHANIC/CONTROLER/TEST/GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
REM GEM_MECHANIC_INTERFACE_BUILDER_TESTS
ECHO.
ECHO FILE : HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GEM_MECHANIC/CONTROLER/TEST/TEST_INTERFACE_BUILDER/HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
Then I'm launching a web page that parse my result and display it in the web browser:
public static function fetchTestResult(&$errorMessage){
$echoString = '';
$failure = false;
$fileContent = '';
$errorMessage = '';
$dbManager = GeneralDbManager::getInstance();
if (file_exists(realpath(dirname(__FILE__)) . '/test_result.txt')) {
#$fileContent = file(realpath(dirname(__FILE__)) . '/test_result.txt');
if ($fileContent === false){
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_RESULT_LOG_ERR', "An error happened while reading the unit tests results log.");
}
else{
unlink(realpath(dirname(__FILE__)) . '/test_result.txt');
if (file_exists(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat')) {
unlink(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat');
}
$echoString = HtmlTagBuilder::createCustomTextArea("TA_UNIT_TEST_RESULT", TextAlign::ALIGN_LEFT, false, 1100, 500);
foreach ($fileContent as $line){
if (StringManager::stringStartWith($line, "FILE :")){
$failure = false;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::TITLE_LINE);
}
elseif (StringManager::stringStartWith($line, "time:")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::WARNING_LINE);
}
elseif (StringManager::stringStartWith($line, "OK (")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::SUCCESS_LINE);
}
elseif ((StringManager::stringStartWith($line, "There ") and strpos($line, "failure") !== false)
or $failure === true){
$failure = true;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
elseif (strpos(strtolower($line), "failure") !== false){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
else{
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::REGULAR_LINE);
}
}
$echoString .= '</DIV><br><br>';
}
}
else{
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_NO_RESULT_LOG_ERR', "You must run the unit test and generate the test log before displaying it.");
}
return $echoString;
}
Additional note: I'm currently getting some information about CGI and it seem that it is pretty inefficient. You might also consider take a look at this post (question and answers):
What is Common Gateway Interface (CGI)?
Related
I have a problem in PHP / Laravel to create multiple zip files synchronously, I copy all commands that is generated and squeeze into the Shell, it executes normally, but when I step into the PHP run it only generates the first file = /.
Controller code.
foreach ($passwords as $p){
if($i == 0){
$command = 'zip -u -j -P '.$p.' '.$dir.'/'.$count.'.zip '.storage_path().'/app/'.$directory.'/'.$file1->getClientOriginalName();
$commands->push($command);
}else{
$command = 'zip --quiet -j -P '.$p.' '.$dir.'/'.$count.'.zip '.storage_path().'/app/'.$directory.'/'.($count+1).'.zip';
$commands->push($command);
}
$count--;
$i++;
}
foreach ($commands as $p){
echo $p.'<br/>';
}
foreach ($commands as $c){
$process = new Process($c);
$process->start();
sleep(10);
if($process->isTerminated()){
sleep(1);
}
if ($errorOutput = $process->getErrorOutput()) {
throw new RuntimeException('Process: ' . $errorOutput);
}
}
Data $commands
The script only generates the file 50.zip.
Not sure if sleep could interfere with subprocess (shell command). Please try:
foreach ($commands as $c){
$process = new Process($c);
// Set the timeout instead of sleeping
$process->setTimeout(10);
$process->start();
// Wait for the process to finish
$process->wait();
if ($errorOutput = $process->getErrorOutput()) {
throw new RuntimeException('Process: ' . $errorOutput);
}
}
wait() call uses usleep in a more fine-grained manner it might help with that.
Does it work like this?
I am new in PHPUnit and i am required to run the test using browser and save the result in xml format.
But every time when i run this code, i got following error:
FatalErrorException: Error: Interface 'PHPUnit_Framework_Test' not found in /usr/share/php/PHPUnit/Framework/TestSuite.php line 83
My code looks like this:
require_once '/var/www/Drillsight/app/autoload.php';
require_once "PHPUnit/Framework/TestSuite.php";
require_once "PHPUnit/TextUI/TestRunner.php";
$run_command = new PHPUnit_TextUI_Command;
$run_command ->run(array('phpunit', '--log-junit', 'results.xml', 'MyPHPUnitTest.php'),true);
Can anybody help in this matter?
Any other recommendation options will be highly appreciated !
Thanks in advance !
Do it really need to be runned in a browser?
I personally use a .bat file containing all my unit test like this
REM GEM_MECHANIC_TESTS
ECHO.
ECHO FILE : GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GENERAL_CONTROLER/TEST/GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
REM GEM_MECHANIC_INTERFACE_BUILDER_TESTS
ECHO.
ECHO FILE : HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
CALL PHPUNIT %~DP0/../../../GENERAL_CONTROLER/TEST/TEST_INTERFACE_BUILDER/HTML_GEM_MECHANIC_MANAGER_TEST.PHP
ECHO.
ECHO.
And run a command like this in my Xampp console:
C:\xampp\htdocs\PC_administration_interface\Controler/script/temp_unit_test.bat >C:\xampp\htdocs\PC_administration_interface\Controler/test_result.txt
Or if you want to do it automatically each night with a windows task:
Launch_xampp.bat
#echo off
tasklist | find /i "xampp-control.exe" && goto :eof
start /b "xampp-control.exe" "C:\xampp\xampp-control.exe"
launch_automatic_test.bat
#echo off
call %~DP0\launch_xampp.bat
call %~DP0\..\..\..\..\xampp_shell.bat
cls
call %~DP0\run_unit_test.bat > "%~DP0\..\test_result.txt"
The method don't matter as much as I export the result in a textfile and than use PHP to parse the output (you can just change the code a bit to produce XML).
public static function fetchTestResult(&$errorMessage){
$echoString = '';
$failure = false;
$fileContent = '';
$errorMessage = '';
$dbManager = GeneralDbManager::getInstance();
if (file_exists(realpath(dirname(__FILE__)) . '/test_result.txt')) {
#$fileContent = file(realpath(dirname(__FILE__)) . '/test_result.txt');
if ($fileContent === false){
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_RESULT_LOG_ERR', "An error happened while reading the unit tests results log.");
}
else{
unlink(realpath(dirname(__FILE__)) . '/test_result.txt');
if (file_exists(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat')) {
unlink(realpath(dirname(__FILE__)) . '/script/temp_unit_test.bat');
}
$echoString = HtmlTagBuilder::createCustomTextArea("TA_UNIT_TEST_RESULT", TextAlign::ALIGN_LEFT, false, 1100, 500);
foreach ($fileContent as $line){
if (StringManager::stringStartWith($line, "FILE :")){
$failure = false;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::TITLE_LINE);
}
elseif (StringManager::stringStartWith($line, "time:")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::WARNING_LINE);
}
elseif (StringManager::stringStartWith($line, "OK (")){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::SUCCESS_LINE);
}
elseif ((StringManager::stringStartWith($line, "There ") and strpos($line, "failure") !== false)
or $failure === true){
$failure = true;
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
elseif (strpos(strtolower($line), "failure") !== false){
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::ERROR_LINE);
}
else{
$echoString .= HtmlTagBuilder::addLineCustomTextArea($line, CustomTextAreaLine::REGULAR_LINE);
}
}
$echoString .= '</DIV><br><br>';
}
}
else{
$errorMessage = $dbManager->getErrorMessage('UNIT_TEST_NO_RESULT_LOG_ERR', "You must run the unit test and generate the test log before displaying it.");
}
return $echoString;
}
I have been working on a powershell script that uses a .txt file to download multiple files from tinyurls. I have been successful in using Jobs to make this happen simultaneously, thanks to those on this forum.
The project requires some pretty large files to be downloaded, and using the current method has no progress indicator. I figured some users might think the program died. Looking for a way give a status of where it is in the download. Here is what I came up with, but I'm lost in how to pipe this information back out to the console. Any suggestions?
#Checks to see if NT-Download folder is on the Desktop, if not found, creates it
$DOCDIR = [Environment]::GetFolderPath("Desktop")
$TARGETDIR = "$DOCDIR\NT-Download"
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
$filepaths = Resolve-Path "files.txt"
Get-Content "$filepaths" | Foreach {
Start-Job {
function Save-TinyUrlFile
{
PARAM (
$TinyUrl,
$DestinationFolder
)
$response = Invoke-WebRequest -Uri $TinyUrl
$filename = [System.IO.Path]::GetFileName($response.BaseResponse.ResponseUri.OriginalString)
$filepath = [System.IO.Path]::Combine($DestinationFolder, $filename)
$totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)
$responseStream = $response.GetResponseStream()
$buffer = new-object byte[] 10KB
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $count
try
{
$filestream = [System.IO.File]::Create($filepath)
$response.RawContentStream.WriteTo($filestream)
$filestream.Close()
while ($count -gt 0)
{
[System.Console]::CursorLeft = 0
[System.Console]::Write("Downloaded {0}K of {1}K", [System.Math]::Floor($downloadedBytes/1024), $totalLength)
$targetStream.Write($buffer, 0, $count)
$count = $responseStream.Read($buffer,0,$buffer.length)
$downloadedBytes = $downloadedBytes + $count
}
"`nFinished Download"
$targetStream.Flush()
$targetStream.Close()
$targetStream.Dispose()
$responseStream.Dispose()
}
finally
{
if ($filestream)
{
$filestream.Dispose();
}
}
}
Save-TinyUrlFile -TinyUrl $args[0] -DestinationFolder $args[1]
} -ArgumentList $_, "$TARGETDIR"
}
Have a look at Write-Progress
PS C:> for ($i = 1; $i -le 100; $i++ )
{write-progress -activity "Search in Progress" -status "$i% Complete:" -percentcomplete $i;}
Far more simple way : rely on Bits:
Start-BitsTransfer -Source $tinyUrl
I am having a problem in sending Arduino data into my database. I am currently using WAMPSERVER. I have an arduino mini w/ ATMEGA 328 and I am using ENC28J60. The problem is I have tried different libraries and examples to send data into the server but I failed. I just notice that some libraries are not compatible with my enc28J60. I have tried UIPEthernet.h, Ethernet.h, etherShield.h and EtherCard.h. The etherShield.h and EtherCard.h seemed to work just fine. But I prefer to use EtherCard.h because I heard etherShield is the older lib. I know a little php.
I think the things that might guide me is to see a working example of using the EtherCard.h library demonstrating the sending of sensor data from arduino into my database. The network setup I am currently working on is that, the ENC28J60 is connected in my home network with an ip address of 192.168.10.10. The server to which I placed the database is my laptop with an IP address of 192.168.10.2. I am placing the php files in this directory C:\wamp\www. I hope I have explained it well. I'm sorry for my English.
I am currently working of a port of my homewatch server from Arduino Uno w Ethernet lib to AVR-NETIO with Ethercard lib (or UIPEthernet).
On the server side there is a Apache/PHP/MySQL server.
To update data on a webserver connected database, you can use POST or GET requests to a php web page. These data can then be added easily to a database and the same or another web page can also display the data of the database.
<?php
require 'dbhelp.php';
//header('Content-type: text/plain');
echo "<html>";
echo "<head>";
echo "<meta name='viewport' content='width=device-width, user-scalable=false, initial-scale=1;'>";
echo "</head>";
echo "<body>" . "<h2>Temperatur und Luftfeuchte</h2>";
// GET requests are sent as a query string on the URL:
// GET index.html?name1=value&name2=value HTTP/1.1
// Host: about.com
// http://192.168.0.40/homewatch/index.php?channel=1&temp=165&humidity=80&datetime=010120131234
if($DEBUG){
print("<pre>");
print_r($_GET);
print("</pre>");
}
openDB();
if( isset($_GET['channel']) && isset($_GET['temp']) && isset($_GET['humidity']) )
{
if($DEBUG)
echo "<p>addData()";
$c=$_GET['channel'];
$t=$_GET['temp'];
$h=$_GET['humidity'];
addData($c, $t, $h);
if($DEBUG)
echo "<p>all done";
//listData();
echo "<p>OK updated data for channel:" . $c . "</p>";
}
else
{
if($DEBUG)
echo "listData()";
//listData();
//echo "<p>missing arg";
}
echo "<p><a href='linechart_hour.php'>Stunden-Übersicht</a></p>";
echo "<p><a href='barchart_days.php'>Tages-Übersicht</a></p>";
echo "<p><a href='http://www.unwetterzentrale.de/uwz/getwarning_de.php?plz=41363&uwz=UWZ-DE&lang=de'>Unwetterwarnungen Jüchen</a></p>";
echo showAllCharts();
//#################################################################################
// see http://code.google.com/p/googlechartphplib/wiki/GettingStarted
//#################################################################################
// don't forget to update the path here
require './lib/GoogleChart.php';
$chart = new GoogleChart('lc', 500, 200);
// manually forcing the scale to [0,100]
$chart->setScale(0,100);
// add one line
$data = new GoogleChartData(array(49,74,78,71,40,39,35,20,50,61,45));
$chart->addData($data);
// customize y axis
$y_axis = new GoogleChartAxis('y');
$y_axis->setDrawTickMarks(false)->setLabels(array(0,50,100));
$chart->addAxis($y_axis);
// customize x axis
$x_axis = new GoogleChartAxis('x');
$x_axis->setTickMarks(5);
$chart->addAxis($x_axis);
echo $chart->toHtml();
//#################################################################################
// END
//#################################################################################
echo "<p>v0.9" . "</body>" . "</html>";
?>
the dbhelp.php file creates the DB automatically if not already exists:
<?php
//global dbhelp.php file
$server="localhost";
$user="root";
$passwd="password";
$names=array(
1 => "Aussen",
2 => "Schlaf",
3 => "Andreas");
$DEBUG=false;
function openDB(){
global $DEBUG;
global $user;
global $passwd;
$link = mysql_connect("localhost", $user, $passwd);
if(!$link){
echo "SqlConnect failed";
echo mysql_error();
}
else
if($DEBUG)
echo "SqlConnect OK";
$query="CREATE database IF NOT EXISTS avrdb;";
$result = mysql_query($query, $link);
if(!$result){
echo "CreateDB failed";
echo mysql_error();
}
else
if($DEBUG)
echo "CreateDB OK";
$result = mysql_select_db("avrdb", $link);
if(!$result){
echo "SelectDB failed";
echo mysql_error();
}
else
if($DEBUG)
echo "SelectDB OK";
$query="CREATE TABLE IF NOT EXISTS `avrtemp` (" .
"`id` int(11) NOT NULL AUTO_INCREMENT, " .
"`channel` int(11), " .
"`temp` int(11), " .
"`humidity` int(11), " .
"`date_time` TIMESTAMP, " .
"PRIMARY KEY (`id`) );";
$result = mysql_query($query, $link);
if(!$result){
echo "CreateTable failed";
echo mysql_error();
}
else
if($DEBUG)
echo "CreateTable OK";
return true;
}
...
function addData($c,$t,$h){
global $DEBUG;
$lastStoredDateTime=getLastStoredDateTime();
if($DEBUG){
echo "<p>" . $c . "</p>\n";
echo "<p>LastDateTime=".$lastStoredDateTime."</p>\n";
}
// add data but do not save seconds (use 00)
$query="INSERT INTO avrtemp (`channel`,`temp`,`humidity`,`date_time`)".
" VALUES ( $c,$t,$h,".
// " DATE_FORMAT(NOW()),".
" DATE_FORMAT('".$lastStoredDateTime."', ".
" '%Y-%c-%d %H:%i') )";
if($DEBUG)
echo "<p>" . $query;
$result = mysql_query($query);
if(!$result){
echo "addData failed";
echo mysql_error();
}
else
if($DEBUG)
echo "addData OK";
}
The Arduino posts (using GET) updated data every 5 minutes. The data arrives at the Arduino via 433MHz wireless sensors every minute or so.
Using the Ethernet Lib the data update is done via
char cBuf[maxBuf+1];
const char getHttpString[] =
"GET /homewatch/index.php?channel=%i&temp=%i&humidity=%i&time=%i\0";
...
// and send data: /index.php?channel=1&temp=165&humidity=80&datetime=010120131234
if (client.connect(server, 80)) {
Serial.println("connected. Send GET...");
snprintf(cBuf, maxBuf,
getHttpString,
sensorData[idxChannel].channel,
sensorData[idxChannel].temp,
sensorData[idxChannel].humidity,
sensorData[idxChannel].time_long
);
Serial.println(F("####"));
Serial.println(cBuf);
Serial.println(F("####"));
client.println(cBuf);
...
https://github.com/hjgode/homewatch/blob/master/arduino/SketchBook/WebClientTemperature/WebClientTemperature.ino:
The string "GET /homewatch/index.php?channel=%i&temp=%i&humidity=%i&time=%i\0" is simply filled with actual sensor data and the server saves that to its database.
The Ethercard lib comes with similar examples: see the examples noipClient, pachube and webclient. Unfortunately I was not yet able to adopt these for my AVR-NETIO.
The code to post (GET) some data to the server I am currently working is
void sendData(int idxChannel){
Serial.print(F("in sendData for idx=")); Serial.println(idxChannel);
byte sd;
int channel=sensorData[idxChannel].channel;
int temp=sensorData[idxChannel].temp;
int humidity=sensorData[idxChannel].humidity;
char* stime="201301011122";
stime=printDateTime((char*)&stime, 13, sensorData[idxChannel].time_long);
if(sensorData[idxChannel].bUpdated==0){
//nothing new
if (MYDEBUG==0){
Serial.println(F("leaving for not updated channel data"));
goto exit_sendData;
}
else
{
sensorData[idxChannel].channel=idxChannel;
sensorData[idxChannel].temp=222;
sensorData[idxChannel].humidity=55;
sensorData[idxChannel].time_long=now();
}
}
// generate two fake values as payload - by using a separate stash,
// we can determine the size of the generated message ahead of time
sd = stash.create();
stash.print("0,");
stash.println((word) millis() / 123);
stash.print("1,");
stash.println((word) micros() / 456);
stash.save();
// generate the header with payload - note that the stash size is used,
// and that a "stash descriptor" is passed in as argument using "$H"
Stash::prepare(PSTR("GET http://$F/homewatch/index.php?channel=$D&temp=$D&humidity=$D&time=$S" "\r\n"
"Host: $F" "\r\n"
"Content-Length: $D" "\r\n"
"\r\n"
"$H"),
website,
channel,
temp,
humidity,
stime,
website, stash.size(), sd);
// send the packet - this also releases all stash buffers once done
ether.tcpSend();
exit_sendData:
lastConnectionTime = now();//millis();
Serial.println(F("...end of sendData()"));
}
As you see, there is a formatted string
PSTR("GET http://$F/homewatch/index.php?channel=$D&temp=$D&humidity=$D&time=$S"
which is filled with variables. $F fills from Flash Memory, $D a number var, $S from a RAM memory string. Using this without my SensorCode (which uses Interrupts) is working.
In an effort to setup a "cron job" like scheduled task on Windows I've setup a Powershell script using code recommended via previous stackoverflow question.
I have some backups that I need to cleanup daily and delete old backups so I created a asp.net script to perform this task - the file name is BackupCleanup.aspx and I have confirmed that the ASP.net script does work when executed on its own by visiting the above url - I however cannot get it to execute using the Powershell script below.
The Powershell Script code I'm using is:
$request = [System.Net.WebRequest]::Create("http://127.0.0.1/BackupCleanup.aspx")
$response = $request.GetResponse()
$response.Close()
I have created this file with a PS1 extension, it shows properly in my os (Windows 2008) - I have tried both manually executing this task by right clicking and choosing "Run with Powershell" and also have scheduled this as a task - both to no avail.
I cannot figure out why the script does not work - any help would be GREATLY appreciated.
Here is the Powershell script I use to call up web pages using IE. Hopefully this will work for you as well.
Function NavigateTo([string] $url, [int] $delayTime = 100)
{
Write-Verbose "Navigating to $url"
$global:ie.Navigate($url)
WaitForPage $delayTime
}
Function WaitForPage([int] $delayTime = 100)
{
$loaded = $false
while ($loaded -eq $false) {
[System.Threading.Thread]::Sleep($delayTime)
#If the browser is not busy, the page is loaded
if (-not $global:ie.Busy)
{
$loaded = $true
}
}
$global:doc = $global:ie.Document
}
Function SetElementValueByName($name, $value, [int] $position = 0) {
if ($global:doc -eq $null) {
Write-Error "Document is null"
break
}
$elements = #($global:doc.getElementsByName($name))
if ($elements.Count -ne 0) {
$elements[$position].Value = $value
}
else {
Write-Warning "Couldn't find any element with name ""$name"""
}
}
Function ClickElementById($id)
{
$element = $global:doc.getElementById($id)
if ($element -ne $null) {
$element.Click()
WaitForPage
}
else {
Write-Error "Couldn't find element with id ""$id"""
break
}
}
Function ClickElementByName($name, [int] $position = 0)
{
if ($global:doc -eq $null) {
Write-Error "Document is null"
break
}
$elements = #($global:doc.getElementsByName($name))
if ($elements.Count -ne 0) {
$elements[$position].Click()
WaitForPage
}
else {
Write-Error "Couldn't find element with name ""$name"" at position ""$position"""
break
}
}
Function ClickElementByTagName($name, [int] $position = 0)
{
if ($global:doc -eq $null) {
Write-Error "Document is null"
break
}
$elements = #($global:doc.getElementsByTagName($name))
if ($elements.Count -ne 0) {
$elements[$position].Click()
WaitForPage
}
else {
Write-Error "Couldn't find element with tag name ""$name"" at position ""$position"""
break
}
}
#Entry point
# Setup references to IE
$global:ie = New-Object -com "InternetExplorer.Application"
$global:ie.Navigate("about:blank")
$global:ie.visible = $true
# Call the page
NavigateTo "http://127.0.0.1/BackupCleanup.aspx"
# Release resources
$global:ie.Quit()
$global:ie = $null
I had the same issue. I manually opened powershell and executed my script and I received "WebPage.ps1 cannot be loaded because running scripts is disabled on this system.".
You have to allow scripts to run
Execute the below in PowerShell
Set-ExecutionPolicy RemoteSigned -Scope LocalMachine