Visual Scripts

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 15

VISUAL BASIC SCRIPTS

ShellExecute method
Run a script or application in the Windows Shell.
Syntax
.ShellExecute "application", "parameters", "dir", "verb", window
.ShellExecute 'some program.exe', '"some parameters with spaces"', , "runas", 1
Key
application The file to execute (required)
parameters Arguments for the executable
dir Working directory
verb The operation to execute (runas/open/edit/print)
window View mode application window (normal=1, hide=0, 2=Min, 3=max, 4=restore,
5=current, 7=min/inactive, 10=default)

Note the different (double " and single ' ) quotes that can be used to delimit paths with spaces.

The runas verb is undocumented but can be used to elevate permissions. When a script is run
with elevated permissions several aspects of the user environment may change: The current
directory, the current TEMP folder and any mapped drives will be disconnected.

runas will fail if you are running in WOW64 (a 32 bit process on 64 bit windows) for example
%systemroot%\syswow64\cmd.exe ...

The ShellExecute method is a member of the IShellDispatch2 object.

Examples

Run a batch script with elevated permissions, flag=runas:

Set objShell = CreateObject("Shell.Application")


objShell.ShellExecute "E:\demo\batchScript.cmd", "", "", "runas", 1

Run a VBScript with elevated permissions, flag=runas:

Set objShell = CreateObject("Shell.Application")


objShell.ShellExecute "cscript", "E:\demo\vbscript.vbs", "", "runas", 1

Set WshShell = WScript.CreateObject("WScript.Shell")


Return = WshShell.Run("cmd.exe", 1, true)

Donde:
cmd.exe –> Es la aplicación que se va a ejecutar.
1 –> Indica que la ventana se abrirá normal, 2 indicaría minimizada y 3 maximizada
true –> Indica que se esperará a que se cierre la aplicación para continuar ejecutando el código,
si no queremos que se espere pondremos false.

BATCH PARA COPIAR DATOS DE DISPOSITIVOS EN UNIDADES USB DE FORMA OCULTA

Archivo CMD

:: (c) Norfipc 2019 - http://norfipc.com


@ECHO OFF
set tiempo=%time:~0,5%
set tiempo=%tiempo::=-%
set fecha=%date:~0%
set fecha=%fecha:/=-%
set file=%fecha% %tiempo%
echo %file%
set ruta="E:\COPIA\%file%"
mkdir %ruta%
MOUNTVOL /R
FOR /F "tokens=2 delims=\ " %%A IN ('REG Query "HKLM\SYSTEM\MountedDevices" /v "\DosDevices\*" ^| FINDSTR
/R /E /C:" 5F[0-9A-F]*"') DO ROBOCOPY %%A\ %ruta% /NODD /V /MIR /R:0 /W:0 /ETA

Archivo VBS

set objshell = createobject("wscript.shell")


objshell.run "FLASHCopy.cmd",vbhide

Mover archivos

Objfso.movefile origen, destino

Ejemplo:
Código
Set objfso = createobject("scripting.filesystemobject")
Objfso.movefile "C:\archivo.txt", "D:\Carpeta"

Borrar archivos

Objfso.deletefile archivo

Ejemplo:
Código
Set objfso = createobject("scripting.filesystemobject")
Objfso.deletefile "C:\archivo.txt"

Copiar archivos

Objfso.copyfile origen, destino, sobreescribir

Ejemplo:
Código
Set objfso = createobject("scripting.filesystemobject")
Objfso.copyfile "C:\archivo.txt", "D:\destino.txt", true

Crear carpetas

Set variable = objfso.createfolder(destino carpeta)

Ejemplo:
Código
Set objfso = createobject("scripting.filesystemobject")
Set micarpeta = objfso.createfolder("C:\carpeta")
Mover carpetas

Objfso.movefolder origen, destino

Ejemplo:
Código
Set objfso = createobject("scripting.filesystemobject")
Objfso.movefolder "C:\Carpeta", "D:\Destino"

Borrar carpetas

Objfso.deletefolder carpeta

Ejemplo:
Código
Objfso.deletefolder "C:\Carpeta"

Copiar carpetas

Objfso.copyfolder origen, destino, sobreescribir

Ejemplo:
Código
Set objfso = createobject("scripting.filesystemobject")
Objfso.copyfolder "C:\Carpeta", "D:\Destino", true

Leer y escribir en archivos

Para el manejo de archivos de texto, debemos de tener en cuenta, la existencia o no del archivo,
y el modo en el que accedemos a él.
Obviamente, si un archivo no existe, no podrémos acceder a él, y a su vez, si abrimos un
archivo en modo de léctura, nunca podremos escribir dentro.

Crear archivos de texto y escribir en ellos

Set variable = objfso.createtextfile(ruta, sobreescribir)

Ejemplo:
Código
Set objfso = createobject("scripting.filesystemobject")
Set archivotexto = objfso.createtextfile("C:\archivo.txt",true) 'creamos el archivo
archivotexto.writeline "Este es el texto que estoy escribiendo" 'escribimos una linea
archivotexto.writeblanklines(2) 'escribimos 2 lineas en blanco
archivotexto.writeline "Aqui mas texto" ' escribimos otra linea de texto
archivotexto.close 'cerramos el archivo

Mirar que al comenzar, hemos creado el archivo y lo hemos asignado a una variable, luego
hemos utilizado el identificador de archivo (variable), para escribir dentro de él, en este caso,
hemos utilizado writeline, que escribe una línea, y agrega un retorno de carro para que si
volvemos a escribir, lo hagamos en una nueva línea, en cambio , si en su lugar, utilizamos write,
el resultado, será que no habrá salto de línea, por lo que todas las oraciones iran quedando una
detrás de la otra. Por último, hemos cerrado el archivo.
Abrir archivos de texto y escribir en ellos

Set variable = objfso.opentextfile(ruta, modo, creación)

Ejemplo:
Código
Set objfso = createobject("scripting.filesystemobject")
Set archivotexto = objfso.opentextfile("C:\archivo.txt",8,true) 'abrimos el archivo
archivotexto.writeline "Este es el texto que estoy escribiendo" 'escribimos una linea
archivotexto.close 'cerramos el archivo

Como se puede ver, al abrir el archivo, hemos indicado la ruta, el modo 8 que se utiliza para
appending o escritura al final de archivo, y true, que quiere decir que en caso de que no exista el
archivo se cree, es decir que de este modo, no solo abrimos el archivo, sino que de no existir,
dicho archivo será creado en el proceso.

Para tener en cuenta, los modos en los que se puede abrir un archivo son:
1- Modo LECTURA
2- Modo ESCRITURA (escribe al principio)
8- Modo APPENDING (escribe al final)

Como se puede ver, al abrir el archivo, hemos indicado la ruta, el modo 8 que se utiliza para
appending o escritura al final de archivo, y true, que quiere decir que en caso de que no exista el
archivo se cree, es decir que de este modo, no solo abrimos el archivo, sino que de no existir,
dicho archivo será creado en el proceso.

Leer desde archivos de texto

Así como abrimos archivos y podemos escribir en ellos, también existe la posibilidad de leer
desde ellos, para lo cual utilizaremos readline, y readall.
Como se puede imaginar, con readline iremos leyendo una a una las líneas del archivo (cada vez
que pongamos readline leeremos solo una), con este, leemos una línea, y el puntero se situa al
final de la línea, para que a la próxima ejecución de esta función, sea la línea siguiente la que
sea leída. Con readall en cambio, leeremos el total de archivo.
Existe además una función llamada skipline, con la cual saltaremos la lectura de una línea.

Ejemplo:
Código
Set objfso = createobject("scripting.filesystemobject")
Set archivotexto = objfso.opentextfile("C:\archivo.txt",1) 'abrimos el archivo
msgbox archivotexto.readline 'leemos una linea, la primera
archivotexto.skipline 'saltamos una linea
msgbox archivotexto.readline 'leemos una linea, la tercera
archivotexto.close 'cerramos el archivo

Atributos de archivos y carpetas

A continuación explicaré el método mediante el cual, se puede obtener, o bien cambiar, los
atribuos de archivos y carpetas (es prácticamente igual para ambas cosas)

Obtener atributos
Set variable = objfso.getfile(ruta)
variable.attributes

Ejemplo:
Código
Set objfso = createobject("scripting.filesystemobject")
Set archivo = objfso.getfile("C:\tutorial.pdf") 'obtenemos el control sobre el archivo pdf
Msgbox archivo.attributes 'mensaje con los attributos del archivo

'Código de ejemplo para crear un VBS


MsgBox "Hola, soy un VBS" & vbCrlf & "Hoy es: "& Date & vbCrlf & "Hora: " & Time,266304

Sub CopyAllFiles()
Dim MyFSO As FileSystemObject
Dim MyFile As File
Dim SourceFolder As String
Dim DestinationFolder As String
Dim MyFolder As Folder
Dim MySubFolder As Folder

SourceFolder = "C:\Users\sumit\Desktop\Source"
DestinationFolder = "C:\Users\sumit\Desktop\Destination"

Set MyFSO = New Scripting.FileSystemObject


Set MyFolder = MyFSO.GetFolder(SourceFolder)

For Each MyFile In MyFolder.Files


MyFSO.CopyFile Source:=MyFSO.GetFile(MyFile), _
Destination:=DestinationFolder & "\" & MyFile.Name, Overwritefiles:=False
Next MyFile

End Sub

Explorar carpetas

Set objShell = CreateObject("Shell.Application")


Set objFolder = objShell.BrowseForFolder _
(WINDOW_HANDLE, "Selecciona una carpeta:", NO_OPTIONS)
Set objFolderItem = objFolder.Self
strPath = objFolderItem.Path
objShell.Explore strPath

CREAR PUNTO DE RESTAURACION

Option Explicit
Dim oSysRestore, sName, makeRestorePoint, sMsg
sMsg= msgBox("Este script creara un punto de restauracion. Continuar?", vbYesNo)
If sMsg = vbNo then wScript.Quit
Set oSysRestore = GetObject( "winmgmts:\\.\root\default:Systemrestore" )
sName = inputBox("Escriba el nombre para el punto de restauracion." & vbCrlf & "El dato sera
incluido.", "Name the restore point")
if sName ="" then wScript.Quit
makeRestorePoint = oSysRestore.CreateRestorePoint( sName, 0, 100 )
msgBox "El punto de restauracion llamado " & sName & " ha sido creado"
set oSysRestore = Nothing
wscript.Quit

Identificar dispositivos en conflicto en el equipo

strComputer = "."
Set objWMIService = GetObject(_
"winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * from Win32_PnPEntity " _
& "WHERE ConfigManagerErrorCode <> 0")
For Each objItem in colItems
Wscript.Echo "Nombre: " & objItem.Name
Wscript.Echo "Descripción: " & objItem.Description
Wscript.Echo "ID Identidad del dispositivo: " & objItem.DeviceID
Wscript.Echo "Fabricante: " & objItem.Manufacturer
Wscript.Echo "Class GUID: " & objItem.ClassGuid
Wscript.Echo "PNP Device ID: " & objItem.PNPDeviceID
Wscript.Echo "Servicio: " & objItem.Service
Next

Dim speaks, speech


speaks="Bienvenido"
Set speech=CreateObject("sapi.spvoice")
speech.Speak speaks

Acceder desde Javascript a elementos HTML


$(‘#jw-video jw-reset’);
$$(‘#jw-video jw-reset’);

APUNTES JAVASCRIPT
//Guarda en variable títulos con clase (‘title’)
Var titles =document.getElementsByClassName(‘title’);

//Para acceder a cada título en forma de variable

Array.from(titles).foreach(function(item){
Console.log(item);
});

for(i=0; i < titles.length; i++){


console.log(titles[i]);
}
//Acceder al segundo elemento de una lista dentro de div class de nombre book-list

cons wmf = document.querySelector(‘#book-list li:nth-child(2).name’);


console.log(wmf);

//Acceder a todos los elementos de una lista con nombre book-list

books = document.querySelectorAll(‘#book-list li .name’);

Array.from(books).foreach(function(book){
Console.log(book);
});

//
function funcl(){
field = document.myForm.userName.value;
alert(field);
}
function func2(){
field = document.myForm.userName.value;
if(field=””){
document.getElementByld("IbUserNarme").style.color=red";
document.myForm.userName.value="Enter user name";
document.myForm.userName.style.color="red";
}
)

//Alert "Hello World!" when the user clicks on an element:


element.addEventListener("click", function(){ alert("Hello World!"); });

What is the difference between screenX/Y, clientX/Y and pageX/Y?

function show_coords(event)
{
var x=event.pageX;
var y=event.pageY;
alert("X coords: " + x + ", Y coords: " + y);
}

document.querySelectorAll(“.jw-video jw-reset”);
pageX/Y gives the coordinates relative to the <html> element in CSS pixels.
clientX/Y gives the coordinates relative to the viewport in CSS pixels.
screenX/Y gives the coordinates relative to the screen in device pixels.

//coordenadas en javascript
document.addEventListener('click', function(e) {console.log('page: ' + e.pageX + ',' + e.pageY, 'client: ' +
e.clientX + ',' + e.clientY, 'screen: ' + e.screenX + ',' + e.screenY)}, false);

En consola se ve esto
page: 590,4656 client: 590,91 screen: 644,195

//Alerta de coordenadas
document.addEventListener('click', function show_coords(event){var x=event.pageX; var y=event.pageY;
alert("X coords: " + x + ", Y coords: " + y);});

//Abrir una ventana con características


window.open(URL,nombre_de_la_ventana,forma_de_la_ventana)
window.open("http://www.desarrolloweb.com", "ventana1", "width=120,height=300,scrollbars=YES")

//Cierra la primera Ventana abierta


window.opener.close()

//Pone el foco
window.opener.focus()
//Quita el foco a la ventana
window.opener.blur()

window.scroll(0,0)
window.opener.scroll(150,200)

XPath in Selenium WebDriver: Complete Tutorial


Xpath=//tagname[@attribute='value']
// : Select current node.
Tagname: Tagname of the particular node.
@: Select attribute.
Attribute: Attribute name of the node.
Value: Value of the attribute.

html/body/div[1]/section/div[1]/div/div/div/div[1]/div/div/div/div/div[3]/div[1]/div/h4[1]/b

Xpath=//*[contains(@type,'sub')]
Xpath=//*[contains(@name,'btn')]
Xpath=//*[contains(@href,'guru99.com')]
Xpath=//*[@type='submit' or @name='btnReset']
Xpath=//input[@type='submit' and @name='btnLogin']
Xpath=//label[starts-with(@id,'message')]

Relative xpath: //*[@class='featured-box']//*[text()='Testing']


Syntax for Locator Usage

Method Target Syntax Example


By ID id= id_of_the_element id=email
By Name name=name_of_the_element name=userName
By Name Using Filters name=name_of_the_element name=tripType value=oneway
filter=value_of_filter
By Link Text link=link_text link=REGISTER
Tag and ID css=tag#id css=input#email
Tag and Class css=tag.class css=input.inputtext
Tag and Attribute css=tag[attribute=value] css=input[name=lastName]
Tag, Class, and Attribute css=tag.class[attribute=value] css=input.inputtext[tabindex=1]
Private Keys As New Selenium.Keys

Private driver As New Selenium.ChromeDriver

Const JS_NEW_WINDOW = "window.open(arguments[0], name);"

Sub test()

driver.Get "http://www.google.com/"

For i = 0 To 9

'If i Then

driver.ExecuteScript JS_NEW_WINDOW, "http://www.google.com/"

driver.SwitchToNextWindow

'driver.FindElementById("lst-ib").SendKeys "some text " & i

'End If

Next

End Sub

Sub LaRuletaDeLaSuerte()

Dim li As WebElements

Dim h As WebElement

Dim objShell

Set objShell = CreateObject("Shell.Application")

objShell.ShellExecute "C:\Program Files\JDownloader 2 (64-Bit)\JDownloader2.exe", , , "runas", 1

driver.Get "https://www.atresplayer.com/antena3/programas/la-ruleta-de-la-suerte/"

driver.FindElementByClass("button_button--lgX0P ").Click

driver.FindElementsByTag("li").Item(1).Click
Application.Wait Now + TimeValue("0:00:03")

currentURL = driver.Url

'MsgBox currentURL

driver.ExecuteScript JS_NEW_WINDOW, "https://eljaviero.com/descargarvideosdelatele/"

driver.SwitchToNextWindow

driver.FindElementById("url_noticia").SendKeys (currentURL)

driver.FindElementByXPath("//*[@id=""boton_enviar""]").Click

End Sub

Sub test()

' Abre el navegador en google

driver.Get "http://www.google.com/"

' Genera 2 pestañas nuevas

For i = 0 To 1

'If i Then

driver.ExecuteScript JS_NEW_WINDOW, "/"

driver.SwitchToNextWindow

Next

currentURL = "site: hidemyna.me Lista de proxies de Estados unidos"

driver.FindElementByXPath("//input[@name=""q""]").SendKeys (currentURL)

driver.SendKeys (Keys.Enter)

driver.SwitchToPreviousWindow

End Sub

PASAR DATOS DE UNA TABLA WEB A EXCEL

Sub table_data()

Dim driver As New ChromeDriver

Dim tabl As Object, rdata As Object, cdata As Object

' "//*[@id="content-section"]/section[1]/div/table"

'Set mihoja = Sheets("Hoja1")

driver.Start "chrome", "https://hidemyna.me"

driver.Get "/en/proxy-list/?country=ES&maxtime=1000&type=45#list"

driver.Window.Maximize
For Each tabl In driver.FindElementsByXPath("//table[@class='proxy__t']")

For Each rdata In tabl.FindElementsByXPath(".//tr")

For Each cdata In rdata.FindElementsByXPath(".//td")

Y=Y+1

Cells(X, Y) = cdata.Text

Next cdata

X=X+1

Y=0

Next rdata

GoTo end_of_for

Next tabl

end_of_for:

End Sub

driver.SwitchToNextWindow

driver.FindElementById("url_noticia").SendKeys (currentURL)

driver.FindElementByXPath("//*[@id='boton_enviar']").Click

End Sub

You might also like