You are on page 1of 71

Cdigo Batch

[Subttulo del documento]


Cdigo Batch

@echo off

Title Ejemplos batch

REM COLOR 0E

REM mode con cols=99 lines=20

cls

::http://www.robvanderwoude.com/errorlevel.php

::https://www.instructables.com/howto/cmd/

::http://www.prophethacker.com/2016/08/best-cmd-commands-used-hacki

::154. source: http://people.virginia.edu/~rtg2t/winadmin/wmic.html

wmic process get workingsetsize,commandline /format:htable > procesos.html

::wmic process | sort

wmic partition get name,bootable,size,type /format:htable >> procesos.html

wmic diskdrive get name,size,model /format:htable >> procesos.html

wmic partition get name,size,type /format:htable >> procesos.html

wmic bios get name,serialnumber,version /format:htable >> procesos.html

wmic csproduct get name,vendor,identifyingNumber /format:htable >> procesos.html

::wmic qfe get description,installedOn /format:csv

wmic qfe get description,installedOn /format:htable >> procesos.html

wmic COMPUTERSYSTEM get TotalPhysicalMemory,caption /format:htable >> procesos.html

wmic nic get macaddress,description /format:htable >> procesos.html

GOTO EndComment

::1. asignar valores a variables


set NOMBRE=Codemonkey

set EDAD=35

::2. asignar valores prestablecidos a variables

set datestr=%date%

::mostrar valores

echo %datestr%

echo Hola %NOMBRE% tienes %EDAD% aos de edad

::3.asignar valor desde teclado

echo Anota algo:

set /p algo=

echo Tu escribiste %algo%

::4. en cmd es: for %c in (*) do @echo %c

echo Contenido (directorio):

for %%c in (*) do @echo %%c

::5.

FOR %%A IN (1 2 3) DO GOTO=%%A

:1

ECHO 1

GOTO 2

:2

ECHO 2

GOTO 3
:3

ECHO 3

:End

::6. Mensajes

::Mensaje tipo Alert en batch

echo Alert en CMD:

Msg * "Hola, mundo en batch"

pause

::Mensaje tipo Alert en Powershell

echo Alert en powershell

powershell
[Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.Me
ssageBox]::show("""Hola mundo""", """Aviso del sistema""")

::7. Mensaje

echo code=Msgbox("Un mensaje!", vbYesNo, "Aviso urgente") > "%temp%\popupBox.vbs"

echo WScript.Quit code >> "%temp%\popupBox.vbs"

cscript /nologo "%temp%\popupBox.vbs"

if %errorlevel%==6 call :Si

if %errorlevel%==7 call :No

echo Terminado!!

exit /b 1

:Si

echo Presionaste Si

exit /b

:No
echo Presionaste No

exit /b

::8. http://stackoverflow.com/questions/31758221/how-do-i-use-the-inputbox-to-add-info-to-a-
batch-file-that-sends-emails-and-requ

echo Hola

call :inputbox "Introduce tu nombre:" "Aviso"

echo Tu introduciste [ %Input% ]

exit /b

:InputBox

set input=

set heading=%~2

set message=%~1

echo wscript.echo inputbox(WScript.Arguments(0),WScript.Arguments(1)) >"%temp%\input.vbs"

for /f "tokens=* delims=" %%a in ('cscript //nologo "%temp%\input.vbs" "%message%"


"%heading%"') do set input=%%a

exit /b

::9. If Else

set user=%USERNAME%

if user=="fer" (Msg * "No existe el usuario 'fer' "

) else (

Msg * "Hola " %user%

if not user=="fer" Msg * "No existe el usuario 'fer' "


::10. Errorlevel

set cadena=""

IF ERRORLEVEL 1 SET ERRORLEV=1

IF ERRORLEVEL 2 SET ERRORLEV=2

IF ERRORLEVEL 3 SET ERRORLEV=3

IF ERRORLEVEL 4 SET ERRORLEV=4

IF ERRORLEVEL 254 SET ERRORLEV=254

IF ERRORLEVEL 255 SET ERRORLEV=255

ECHO ERRORLEVEL = %ERRORLEV%

::11. Errorlevel

REM Reset variables

FOR %%A IN (1 10 100) DO SET ERR%%A=

REM Check error level hundredfolds

FOR %%A IN (0 1 2) DO IF ERRORLEVEL %%A00 SET ERR100=%%A

IF %ERR100%==2 GOTO 200

IF %ERR100%==0 IF NOT "%1"=="/0" SET ERR100=

REM Check error level tenfolds

FOR %%A IN (0 1 2 3 4 5 6 7 8 9) DO IF ERRORLEVEL %ERR100%%%A0 SET ERR10=%%A

IF "%ERR100%"=="" IF %ERR10%==0 SET ERR10=

:1

REM Check error level units

FOR %%A IN (0 1 2 3 4 5) DO IF ERRORLEVEL %ERR100%%ERR10%%%A SET ERR1=%%A


REM Modification necessary for errorlevels 250+

IF NOT ERRORLEVEL 250 FOR %%A IN (6 7 8 9) DO IF ERRORLEVEL %ERR100%%ERR10%%%A SET


ERR1=%%A

GOTO End

:200

REM In case of error levels over 200 both

REM tenfolds and units are limited to 5

REM since the highest DOS error level is 255

FOR %%A IN (0 1 2 3 4 5) DO IF ERRORLEVEL 2%%A0 SET ERR10=%%A

IF ERR10==5 FOR %%A IN (0 1 2 3 4 5) DO IF ERRORLEVEL 25%%A SET ERR1=%%A

IF NOT ERR10==5 GOTO 1

:End

REM Clean up the mess and show results

SET ERRORLEV=%ERR100%%ERR10%%ERR1%

FOR %%A IN (1 10 100) DO SET ERR%%A=

ECHO ERRORLEVEL %ERRORLEV%

::12. Uso de Msg e InputBox

set nombre=Ariel

set edad=35

set direccion=Aldama no. 102, Col. Valverde

echo Ejemplo de MSG

Msg * "Datos( nombre: %nombre% , edad: %edad% , direccion: %direccion% )"

pause
echo Ejemplo de InputBox

call :inputbox "Introduce tu nombre:" "Bienvenido"

echo Introduciste: %Input%

exit /b

:InputBox

set input=

set heading=%~2

set message=%~1

echo wscript.echo inputbox(WScript.Arguments(0),WScript.Arguments(1)) >"%temp%\input.vbs"

for /f "tokens=* delims=" %%a in ('cscript //nologo "%temp%\input.vbs" "%message%"


"%heading%"') do set input=%%a

exit /b

::13 Inputbox (*.vbs) (https://ss64.com/vb/inputbox.html)

SETLOCAL

SET _prompt=%1

::Create the VBS script with an echo statement:

ECHO Wscript.Echo Inputbox("Introduce %_prompt%","Entrada requerida")>%TEMP%\~input.vbs

:s_GetInput

:: Run the vbScript and save the output

FOR /f "delims=/" %%G IN ('cscript //nologo %TEMP%\~input.vbs') DO set _string=%%G

:: Delete the VBS file

DEL %TEMP%\~input.vbs

:: Display the result

SET _string

ENDLOCAL & SET _input=%_string%

echo Introduciste %_input%

Msg * "Introduciste %_input% "


::14 Mandar un ping

for /L %%f in (1 0 2) do (

ping 216.58.193.14 | call findstr ":D"

if errorlevel 1 echo %date% %time% : Not Found

choice /t 5 /c y /d y /n /m "" >nul

::15 Mandar un ping

:LoopBack

FOR /F "delims=@" %%a IN ( 'ping 127.0.0.1' ) DO ( SET TRIP_TIME=%%a )

ECHO %TRIP_TIME%

REM Prompts you to enter a choice with a timeout of five seconds.

CHOICE /C YN /D N /N /T 5

call :LoopBack

::16 'Funciones'

::Funcin Hola

:Hola

echo Hola %username%


::Funcin Adios

:Adios

echo Adios %username%

::17. funciones annimas (http://stackoverflow.com/questions/10149194/something-like-a-


function-method-in-batch-files)

setlocal

set "anonymous=/?"

:: calling the anonymous function

call :%%anonymous%% a b c 3>&1 >nul

:: here the anonymous function is defined

if "%0" == ":%anonymous%" (

echo(

echo Funcion anonima call:

echo %%1=%1 %%2=%2 %%3=%3

exit /b 0

)>&3

::end of the anonymous function

::18. Info del sistema

echo Fecha actual %DATE%

echo Hora actual %TIME%

echo Nombre del PC %COMPUTERNAME%

echo Nombre del usuario %USERNAME%

echo Directorio raiz del HD %SYSTEMROOT%


echo Directorio en que te encuentras %CD%

echo Numero de procesadores %NUMBER_OF_PROCESSORS%

::19. Info del sistema con espacio (http://stackoverflow.com/questions/4285270/msg-in-batch-


needs-new-line-how)

setlocal EnableDelayedExpansion

set lf=^

rem Two blank lines (without spaces are neccessary)

Msg * "Hoi %username%!lf! je kunt nu alle vensters sluiten en AutoCAD opniew opstarten"

echo Error %errorlevel%

::20. Escribir archivo txt y ver contenido con Msg

echo Hola %username% >msg.txt

echo. >>msg.txt

echo Has entrado en modo usuario >>msg.txt

type msg.txt | msg *

echo Terminado

::21. Uso de CHOICE

:START

CLS

CHOICE /C CN /T 10 /D C /N /M "Selecciona C para la Calculadora o N para el Bloc de notas"


IF errorlevel 2 goto N

IF errorlevel 1 goto C

:C

START CALC.EXE

GOTO START

:N

START NOTEPAD.EXE

GOTO START

::22. Crear y eliminar directorios

set array=1 2 3 4 5

for %%c in (%array%) do @mkdir %%c

for %%c in (%array%) do @rmdir %%c

::23. Operadores

if "Fer" EQU "Fer" echo Son iguales 1

if "Fer" NEQ "Ariel" echo No son iguales 2

if 4 LSS 30 echo No son iguales 3

if "Fer" LEQ "Fer" echo Son relativamente iguales 4

if 67 GTR 45 echo No son iguales 5

if 67 GEQ 66 echo No son iguales 6

if NOT "Fer" EQU "Fern" echo No son iguales 7

::24. Info del sistema

echo Guardando informacion del sistema en un CSV


MSINFO32 /REPORT "%temp%\reporte.csv"

Msg * "Hecho!"

::25. Reiniciar todas las conexiones (https://norfipc.com/comandos/usar-linea-comandos-


windows-7-l-o.html)

net.exe stop "dhcp client"

net.exe stop "dns client"

net.exe stop "network connections"

net.exe start "dhcp client"

net.exe start "dns client"

net.exe start "network connections"

::26 Batch tiles

REM historial

doskey /history

REM Estado de los puertos

netstat -AO -04

REM Ino del sistema

SYSTEMINFO > "%TEMP%\reporte.csv"

::27. Uso de RUNDLL32 (https://norfipc.com/comandos/como-usar-comando-rundll32-windows-


usos-practicos.php)

echo Propiedades del sistema

Rundll32 Shell32.dll,Control_RunDLL Sysdm.cpl,,1

echo Programas y caractersticas

RunDll32.exe shell32.dll,Control_RunDLL appwiz.cpl,,0

REM Opciones de internet


echo Abre en la ventana de Propiedades de Internet, la pestaa General

Rundll32 Shell32.dll, Control_RunDLL Inetcpl.cpl,,0

echo Resolucin de pantalla

rundll32.exe shell32.dll,Control_RunDLL desk.cpl

echo Configuracin del protector de pantalla

rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,1

echo Personalizacin

rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,2

echo Opciones de energa

RunDll32.exe Shell32.dll,Control_RunDLL powercfg.cpl

echo Opciones de energa Configuracin avanzada

RunDll32.exe Shell32.dll,Control_RunDLL powercfg.cpl,,0

echo Region

Rundll32 Shell32.dll,Control_RunDLL Intl.cpl,,0

echo Sonido

Rundll32 Shell32.dll,Control_RunDLL Mmsys.cpl,,0

echo Telfono y modem

rundll32.exe shell32.dll,Control_RunDLL telephon.cpl,,1

echo Propiedades del teclado

RunDll32.exe shell32.dll,Control_RunDLL main.cpl @1

echo Propiedades del raton

RunDll32.exe shell32.dll,Control_RunDLL main.cpl @0

echo Dispositivos de juego

rundll32.exe shell32.dll,Control_RunDLL joy.cpl,,0

echo Quitar hardware de forma segura

RunDll32.exe shell32.dll,Control_RunDLL hotplug.dll

echo Fecha y hora

RunDll32.exe shell32.dll,Control_RunDLL timedate.cpl

echo Conexiones de red


RunDll32.exe shell32.dll,Control_RunDLL ncpa.cpl

echo Panel de Cuentas de usuario

RunDll32.exe shell32.dll,Control_RunDLL nusrmgr.cpl

echo Panel del Centro de actividades

RunDll32.exe shell32.dll,Control_RunDLL wscui.cpl

echo Firewall de Windows

RunDll32.exe shell32.dll,Control_RunDLL firewall.cpl

echo Lapiz y entrada tactil

rundll32.exe shell32.dll,Control_RunDLL tabletpc.cpl

echo Opciones de carpeta

RunDll32.exe shell32.dll,Options_RunDLL 0

echo Propiedades de la barra de tareas

RunDll32.exe shell32.dll,Options_RunDLL 1

echo Conectar a unidad de red

RunDll32.exe shell32.dll,SHHelpShortcuts_RunDLL Connect

echo Carpeta Impresoras

Rundll32 Shell32.dll,SHHelpShortcuts_RunDLL PrintersFolder

echo Carpeta de Fuentes del equipo

Rundll32 Shell32.dll,SHHelpShortcuts_RunDLL FontsFolder

echo Acerca de Windows

RunDll32.exe SHELL32.DLL,ShellAboutW

echo Hibernar el equipo

RunDll32.exe powrprof.dll,SetSuspendState

echo Administrador de dispositivos

RunDll32.exe devmgr.dll DeviceManager_Execute

echo Bloquear pantalla

RunDll32 user32.dll,LockWorkStation

echo Agregar ubicacin de red

rundll32.exe shwebsvc.dll,AddNetPlaceRunDll
echo Herramienta Asesor de contenido

RunDll32.exe msrating.dll,RatingSetupUI

echo Asistente para contrasea olvidada

RunDll32.exe keymgr.dll,PRShowSaveWizardExW

echo Organizar Favoritos de Internet Explorer

Rundll32.exe shdocvw.dll,DoOrganizeFavDlg

echo Interfaz de usuario de la impresora

Rundll32 Printui.dll,PrintUIEntry /?

::28. Uso de Start

:start

START /B ping norfipc.com

cls

timeout /nobreak 20

goto start

::29. Uso de Start (https://norfipc.com/comandos/como-usar-comando-start-windows-


aplicaciones-practicas.php)

echo Hola

start https://www.twitter.com/CarraroAriel

timeout /nobreak 04

start firefox https://www.twitter.com/CarraroAriel

timeout /nobreak 03

echo Bajando un doc

START http://sitio-web/descargas/archivo.zip

START %USERPROFILE%\Downloads
::30. Uso de SHUTDOWN

SHUTDOWN /S /T 10 ::Apagar en 10 segundos.

SHUTDOWN /S /P ::Apaga el equipo inmediatamente.

SHUTDOWN /R /C "Se va a reiniciar el equipo para." ::Se inicia el apagado pero se muestra un
mensaje con el motivo.

SHUTDOWN /R /T 10 /C "Reiniciando en 10 segundos" ::Reinicia el equipo en 10 segundos y


muestra previamente un mensaje de advertencia.

SHUTDOWN /I ::Abre una ventana de dialogo con distintas opciones para el apagado.

SHUTDOWN /O /R /T 10 ::Se reinicia el equipo en diez segundos, pero asegurando que se


muestren las opciones avanzadas de inicio.

SHUTDOWN /H /F ::Se hiberna el equipo y se cierran de forma forzada aplicaciones abiertas.

::31. Tasklist

TASKLIST /V ::Muestra informacin detallada de cada tarea ejecutndose.

TASKLIST /SVC ::Muestra informacin adicional de los servicios hospedados en cada proceso.

TASKLIST /M modulo ::Muestra todas las tareas que usan un mdulo DLL o EXE especificado. Si
no se indica el modulo se muestran todos los mdulos cargados.

TASKLIST /FO formato ::Especifica el formato de salida. Puede ser: "TABLE", "LIST", "CSV".

TASKLIST /NH ::Si se usan los formatos "TABLE" y "CSV", especifica que el "encabezado de
columna" no se debe mostrar.

TASKLIST /FI filtro ::Filtra la informacin que se solicita con un criterio especificado.

::32. Uso de Tasklist

echo Guardando tasklist...

TASKLIST /V /FO CSV > list.csv

TASKLIST /SVC /FO LIST > list.txt

TASKLIST /V /FI "STATUS eq running"


TASKLIST /M ntdll.dll

::33.Uso de taskkill

echo Finalizar el proceso del Bloc de notas de Windows.

TASKKILL /F /IM notepad.exe

echo Cierra el proceso con el nmero de identidad 1250.

TASKKILL /PID 1250

echo Cierra la consola de CMD y todos los procesos secundarios iniciados por ella.

TASKKILL /F /IM cmd.exe /T

echo Permite detener de forma forzada cualquier script escrito en VBScript de forma forzada que
sea imposible finalizar de otro modo.

TASKKILL /F /IM wscript.exe

echo Permite cerrar el explorador de Windows ante un bloqueo y a continuacin volverlo a iniciar.

TASKKILL /F /IM explorer.exe & start explorer.exe

echo Permite cerrar cualquier tarea en Windows que no responde.

taskkill.exe /f /fi "status eq Not Responding"

::34. WINSAT

WINSAT QUERY

::con Powershell Get-WmiObject -Class Win32_WinSAT

::35. Bajar vdeos de Youtube (https://norfipc.com/comandos/como-bajar-videos-desde-youtube-


con-youtube-dl.php)

::https://rg3.github.io/youtube-dl/index.html

Rem video: https://www.youtube.com/watch?v=6YziZ1FlAWs

SET/p ruta=Escribe o pega la ruta del video:

echo.

echo.
youtube-dl.exe %ruta%

::36 Llamando a funciones y mandando parametros

echo.Mandando difrentes argumentos a la funcion myDosFunc

call:myDosFunc 100 Hola_Mundo

call:myDosFunc 100 "para mi"

call:myDosFunc 100,"para ti"

call:myDosFunc 100,for me

echo.&pause&goto:eof

::--------------------------------------------------------

::-- Function section starts below here

::--------------------------------------------------------

:myDosFunc

echo.

echo. Aqui la funcion ejecuta los parametros/comandos

echo. Esto puede ser %~1 de esto %~2.

goto:eof

::37. Llamando a funciones

echo.1 Vamos a ejecutar myDosFunc

call:myDosFunc

echo.2 Regrese de myDosFunc

echo.&pause&goto:eof

::--------------------------------------------------------

::-- Function section starts below here

::--------------------------------------------------------

:myDosFunc
echo. A. Aqui myDosFunc ejecuta los comandos

echo. B. Aqui podria hacer otras cosas

goto:eof

::38. Retornando valores

set "var1=YoSoyElPrimero"

echo.var1 Antes: %var1%

call:myGetFunc var1

echo.var1 Despues: %var1%

echo.&pause&goto:eof

::--------------------------------------------------------

::-- Function section starts below here

::--------------------------------------------------------

:myGetFunc

set "%~1=YoSoyElUltimo"

goto:eof

::39. Variables locales

set "aStr=Espero no cambiar cuando se llame a la funcion"

set "var1=Cambie?"

echo.aStr 1. Antes: %aStr%

echo.var1 2. Antes: %var1%

call:myGetFunc var1

echo.aStr 1. Despues : %aStr%

echo.var1 2. Despues : %var1%


echo.&pause&goto:eof

::--------------------------------------------------------

::-- Function section starts below here

::--------------------------------------------------------

:myGetFunc

SETLOCAL

set "aStr=DosTips"

set "%~1=%aStr%"

ENDLOCAL

goto:eof

::40. Paso de agrumentos

echo Introduciste %~1

set parametro=%~1

call:myDosFunc Hola %~1

echo.

echo.&pause&goto:eof

::--------------------------------------------------------

::-- Function section starts below here

::--------------------------------------------------------

:myDosFunc

echo.Hola %parametro%

goto:eof

::41 fibonacci

set "fst=0"

set "fib=1"

set "limit=1000000000"
call:myFibo fib,%fst%,%limit%

echo.The next Fibonacci number greater or equal %limit% is %fib%.

echo.&pause&goto:eof

::--------------------------------------------------------

::-- Function section starts below here

::--------------------------------------------------------

:myFibo -- calculate recursively the next Fibonacci number greater or equal to a limit

:: -- %~1: return variable reference and current Fibonacci number

:: -- %~2: previous value

:: -- %~3: limit

SETLOCAL

set /a "Number1=%~1"

set /a "Number2=%~2"

set /a "Limit=%~3"

set /a "NumberN=Number1 + Number2"

if /i %NumberN% LSS %Limit% call:myFibo NumberN,%Number1%,%Limit%

(ENDLOCAL

IF "%~1" NEQ "" SET "%~1=%NumberN%"

goto:eof

::42. Retornar valores

set "aStr=Expect no changed, even if used in function"

set "var1=Expect changed"

echo.aStr before: %aStr%


echo.var1 before: %var1%

call:myGetFunc var1

echo.aStr after : %aStr%

echo.var1 after : %var1%

echo.&pause&goto:eof

::--------------------------------------------------------

::-- Function section starts below here

::--------------------------------------------------------

:myGetFunc - passing a variable by reference

SETLOCAL

set "aStr=DosTips"

( ENDLOCAL

set "%~1=%aStr%"

goto:eof

:myGetFunc2 - passing a variable by reference

SETLOCAL

set "aStr=DosTips"

ENDLOCAL&set "%~1=%aStr%" &rem THIS ALSO WORKS FINE

goto:eof

::43.

:myFunctionName -- function description here

:: -- %~1: argument description here

SETLOCAL

REM.--function body here

set LocalVar1=...
set LocalVar2=...

(ENDLOCAL & REM -- RETURN VALUES

IF "%~1" NEQ "" SET %~1=%LocalVar1%

IF "%~2" NEQ "" SET %~2=%LocalVar2%

GOTO:EOF

::44. Msg

Msg * "Creando un Msgbox"

pause

echo MsgBox "Escribir un script y despues llamarlo.", 64, "Aviso del sistema" >
%temp%\mensaje.vbs

start %temp%\mensaje.vbs

MsgBox "mensaje con icono de Error",0, "Error"

MsgBox "mensaje con icono de Error",16, "Error"

MsgBox "mensaje con icono de interrogacion",32, "Interrogacion"

MsgBox "mensaje con icono de advertencia",48, "Advertencia"

MsgBox "mensaje con icono de informacion",64, "Informacin"

MsgBox "mensaje con icono de Aplicacion",4096, "Aplicacion"

::45. Uso de Set

title Nombre y apellidos

set/p nombre=Escribe tu nombre y oprime Enter.

set/p apellido=Escribe tu primer apellido?

set/p apellido2=Escribe tu segundo apellido?

echo.

echo Tu nombre completo es %nombre% %apellido% %apellido2%

pause >nul
exit

::46.

SET /P busqueda=Escribe el termino a buscar:

START http://www.google.com/search?q=%busqueda%

::47.

cd /d "%~dp0"

echo msgbox "Este es un simple mensaje">123.vbs

echo Set fso = CreateObject("scripting.filesystemobject")>>123.vbs

echo fso.DeleteFile ".\123.vbs">>123.vbs

start 123.vbs

::48.

call:myFunctionName

:: -- %~1: argument description here

SETLOCAL

REM.--function body here

set LocalVar1="Hola %USERNAME%"

set LocalVar2=", tu sistema es %OS%"

(ENDLOCAL & REM -- RETURN VALUES

IF "%~1" NEQ "" SET %~1=%LocalVar1% echo %LocalVar1%

IF "%~2" NEQ "" SET %~2=%LocalVar2% echo %LocalVar2%

GOTO:EOF
::49. Uso de CHOICE

:BEGIN

CLS

CHOICE /N /C:123 /M "Escoge un numero (1, 2, or 3)"%1

IF ERRORLEVEL ==3 GOTO THREE

IF ERRORLEVEL ==2 GOTO TWO

IF ERRORLEVEL ==1 GOTO ONE

GOTO END

:THREE

ECHO Tu elegiste 3

GOTO END

:TWO

ECHO Tu elegiste 2

GOTO END

:ONE

ECHO tu elegiste 3

:END

pause

::50. Uso de SET

:start

ECHO.

ECHO 1. Print Hello

ECHO 2. Print Bye

ECHO 3. Print Test


set choice=

set /p choice=Type the number to print text.

if not '%choice%'=='' set choice=%choice:~0,1%

if '%choice%'=='1' goto hello

if '%choice%'=='2' goto bye

if '%choice%'=='3' goto test

ECHO "%choice%" is not valid, try again

ECHO.

goto start

:hello

ECHO HELLO

goto end

:bye

ECHO BYE

goto end

:test

ECHO TEST

goto end

:end

pause

::51. Uso de IF, IF-ELSE , Msg

set arch=temporal.txt

set doc=noExiste.txt

if exist %arch% Msg * "Existe archivo: %arch%"

pause

if exist %doc% (Msg * "Existe archivo: %doc%") else (Msg * "No existe archivo: %doc%")
::52. Uso de shift

:Bucle

if "%1"=="" goto :Continuar

echo "Hola %username%"

shift

goto Bucle

:Continuar

::53. USO DE %RANDOM%, set /a

set aleatorio=%RANDOM%

set /a x="%aleatorio%-2000"

set /a doble_x="%x%*2"

set /a mitad_x="%x%/2"

echo Numeros: %aleatorio% , %x% , %doble_x% , %mitad_x%

::54.

SETLOCAL ENABLEEXTENSIONS

SET /A errno=0

SET /A ERROR_HELP_SCREEN=1

SET /A ERROR_SOMECOMMAND_NOT_FOUND=2

SET /A ERROR_OTHERCOMMAND_FAILED=4

time /t
IF %ERRORLEVEL% NEQ 0 SET /A errno^|=%ERROR_SOMECOMMAND_NOT_FOUND%

date /t

IF %ERRORLEVEL% NEQ 0 (

SET /A errno^|=%ERROR_OTHERCOMMAND_FAILED%

EXIT /B %errno%

::55.

set globalvar = 5

SETLOCAL

set var = 13145

set /A var = %var% + 5

ENDLOCAL

echo %var%

echo %globalvar%

::56.

echo.

echo %1 %2 %3

echo.

::59.Reinicia todos los servicios de red, vaca y restablece la cach, para eso escribe los siguientes
comandos y pulsa Enter despus de cada uno:

ARP -d * ::Vaca la cach de ARP

IPCONFIG /FLUSHDNS ::Vaca la cach de DNS


NBTSTAT R && NBTSTAT -r & NBTSTAT -c ::Purga y vuelve a cargar la cach NetBIOS

NBTSTAT RR ::Se vuelve a registrar con WINS

IPCONFIG /REGISTERDNS ::Se vuelven a registrar los DNS

::Si no se resolvi el problema, restablece el catalogo de Winsock con el comando NETSH.Para eso
escribe en la consola y presiona la tecla Enter:

NETSH WINSOCK RESET

::58 tracert

tracert /?

tracert 11.1.0.1

tracert 22.110.0.1

tracert www.google.com

tracert 148.215.1.1

tracert 148.215.24.39

::57. IP, PING, TRACERT

ipconfig /all

ping google.com

tracert google.com

PAUSE

::60. PING, IPCONFIG, NSLOOKUP, NETSTAT, ARP, ROUTE, TRACERT

::PING, para probar la conectividad


::IPCONFIG, para mostrar la configuracin de la red

::NSLOOKUP, para probar los servidores DNS

::NETSTAT, para conocer la estadstica de las conexiones a red

::ARP, para resolver conflictos de direcciones

::ROUTE, para ver rutas recorridas por un paquete en la red

::TRACERT, para trazar una ruta en la red

echo [ Comandos de Red ]

echo ** PING:

ping 127.0.0.1

echo.

echo ** IPCONFIG:

ipconfig /all

echo.

echo **NSLOOKUP:

NSLOOKUP www.google.com

echo.

echo ** NETSTAT:

NETSTAT -e

echo.

echo **ARP:

ARP -v

echo.

echo ** ROUTE:

ROUTE PRINT

echo.

echo **TRACERT:

TRACERT 148.215.1.1

echo.

echo ********************************************
::61.

if exist %JAVA_HOME% (

Msg * "Existe"

) else (

Msg * "No existe"

::62. Ver directorios

echo Listar directorios:

for /D %%i in ("C:\Users\USUARIO\Desktop\ejemplosProg\*") do @echo %%i

echo Listar todo:

for %%i in (*) do @echo %%i

echo Encontrar

CD \Work

FOR /D /r %%G in ("*") DO echo Encontramos: %%~nxG

echo Listar:

for /D %%i in ("C:\Users\USUARIO\Desktop\ejemplosProg\*") do @echo %%i

::64. Password

powershell -Command $pword = read-host "Enter password:" -AsSecureString ;


$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ;
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt & set /p
password=<.tmp.txt & del .tmp.txt
::64. Ver contenido de un txt (http://tldp.org/LDP/abs/html/dosbatch.html)

REM VIEWDATA

REM INSPIRED BY AN EXAMPLE IN "DOS POWERTOOLS"

REM BY PAUL SOMERSON

IF !%1==! GOTO VIEWDATA

REM IF NO COMMAND-LINE ARG...

FIND "%1" C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.TXT

GOTO EXIT0

REM PRINT LINE WITH STRING MATCH, THEN EXIT.

:VIEWDATA

TYPE C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.TXT | MORE

REM SHOW ENTIRE FILE, 1 PAGE AT A TIME.

:EXIT0

::65. Crear log

echo Enter your name:

set /p name=

echo Enter your password:

set /p pword=

cls

set hora=%time%

set fecha=%date%

for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b

set ip=%ip:~1%
set LOG=Nombre: %name% , Usuario: %USERNAME%, Password: %pword%, Maquina:
%COMPUTERNAME%, Sistema: %OS%, Dominio: %USERDOMAIN%, hora: %hora% , fecha:
%fecha%, IP: %ip%

echo %LOG% >> instalado.dat

Msg * "Antivirus F-Secure activado"

::66. Norfipc scripts https://norfipc.com/utiles/tutorialbatch1.html

@echo off

echo Hola Mundo

pause

exit

::67. Norfipc scripts https://norfipc.com/utiles/tutorialbatch1.html

copy C:\archivo.txt C:\archivo2.txt

CD copy archivo.txt archivo2.txt

DEL /F /Q archivo.txt

move C:\uno\archivo.txt C:\dos\archivo2.txt

COPY copiame.txt copiado.txt

MOVE copiado.txt C:\copiado.txt

echo Creando un Archivo de texto > nuevo.txt

echo Esta es la Segunda linea >> nuevo.txt

echo Y esta es la Siguiente >> nuevo.txt

echo Esto esta genial >> nuevo.txt

SET numero1 = 2

SET numero2 = 43

SET /A suma = %numero1% + %numero2%

echo %suma%

ipconfig|FINDSTR /C:"Mscara de subred"


COPY D:\NOEXISTE C:\ || ECHO No se pudo copiar el archivo

START calc.exe && ECHO La calculadora se inicio con xito.

DIR C:\ >Lista_de_C.txt & DIR D:\ >Lista_de_D.txt

FIND /i "Alberto" < texto.txt > resultado.txt

MEM /C >> MemLog.txt

DATE /T >> MemLog.txt

TYPE texto.txt > texto.html

CMD /K IPCONFIG /ALL

CMD /C START http://google.com

::68. CHOICE (http://www.robvanderwoude.com/choice.php)

CHOICE /C ABCDN /N /T 10 /D C /M "Format drive A:, B:, C:, D: or None?"

IF ERRORLEVEL 1 SET DRIVE=drive A:

IF ERRORLEVEL 2 SET DRIVE=drive B:

IF ERRORLEVEL 3 SET DRIVE=drive C:

IF ERRORLEVEL 4 SET DRIVE=drive D:

IF ERRORLEVEL 5 SET DRIVE=None

ECHO You chose to format %DRIVE%

::75. Uso del comando tracert

::tracert 148.215.24.39

::tracert www.google.com

::tracert www.redalyc.org
::74. Uso del comando route

::route print

::route print > rutas.txt

::73. Uso del comando arp

::ARP -A ::- Muestra la tabla arp o sea las asignaciones que se encuentran en cache

::ARP -V ::- Muestra las entradas de forma detallada

::ARP -D ::- Permite borrar las entradas manualmente

::ARP -D* ::- Vaca completamente la cache de arp

::ARP -S ::- Asocia una direccin IP de internet con una direccin fsica de la tarjeta de forma
permanente

::72. Uso del comando netstat

::Mostrar todas las conexiones: NETSTAT -AO 04

::Ver estadsticas de conexiones por protocolos: NETSTAT -AOS 04

::Ver los puertos y direcciones de origen en formato numrico: NETSTAT -AON 04

::Ver conexiones solo del protocolo TCPv4: NETSTAT -AON -P TCP 04

::Ver los puertos abiertos a la escucha: NETSTAT -AN 04|FINDSTR /C:LISTENING

::Ver los puertos y conexiones establecidas: NETSTAT -ANO -P TCP 04|FINDSTR /C:ESTABLISHED

::Crear informe de las conexiones establecidas:

::NETSTAT -ANO -P TCP 04|FINDSTR /C:ESTABLISHED>Conex.txt

::Aplicaciones involucradas en conexiones con el exterior:

::NETSTAT -ANOB -P TCP 04|FINDSTR /C:ESTABLISHED

::Informe de las Aplicaciones involucradas en conexiones con el exterior:


::NETSTAT -ANOB -P TCP 04|FINDSTR /C:ESTABLISHED>Aplic.txt

::netstat

::netstat -o

::netstat -r

::netstat -a ::muestra todas las conexiones y puertos de escucha

::netstat -n ::muestra los puertos y direcciones en formato numrico.

::netstat -b ::muestra el nombre del programa que inici la conexin

::netstat -e ::muestra estadsticas de datos enviados, recibidos

::netstat -an

::netstat -aon 6 > informe.txt

::netstat -T ::Muestra el estado de la carga de la conexin actual.

::netstat -X ::Muestra conexiones NetworkDirect, escuchas y los extremos compartidos.

::netstat -Y ::Muestra la plantilla de conexin TCP para todas las conexiones.

::NETSTAT -AN|FINDSTR /C:LISTENING ::Conocer los puertos abiertos en el equipo a la escucha

::CMD.EXE /K NETSTAT -AN|FINDSTR /C:LISTENING

::CMD.EXE /K NETSTAT -BO 10

::NETSTAT -BO 10

::TASKLIST /SVC /FI "PID eq ID" ::conocer la aplicacin que inicia un proceso

::CMD.EXE /K TASKLIST /SVC /FI "PID eq ID" ::conocer la aplicacin que inicia un proceso

::TASKKILL /F /IM KMService.exe TASKKILL /F /IM NombreProceso

::TASKKILL /F /IM TUProgSt.exe

::71. Uso del comando nslookup

::nslookup www.redalyc.org

::nslookup www.facebook.com

::nslookup www.google.com

::nslookup 8.8.8.8
::nslookup 208.67.220.220

::nslookup 10.30.112.220

::nslookup 208.67.222.222

::nslookup es.wikipedia.org

::70. Uso del comando ipconfig

::ipconfig /all y oprime Enter.

::cmd /k IPCONFIG

::solucionar problema de red

::ARP -d * Vaca la cach de ARP

::IPCONFIG /FLUSHDNS Vaca la cach de DNS

::NBTSTAT R && NBTSTAT -r & NBTSTAT -c Purga y vuelve a cargar la cach NetBIOS

::NBTSTAT RR Se vuelve a registrar con WINS

::IPCONFIG /REGISTERDNS Se vuelven a registrar los DNS

::NETSH WINSOCK RESET

::solucionar problema de red

::69. Uso del comando ping

::cmd /k ping 127.0.0.1

::ping google.com -n 5

::ping google.com -t

::ping -a norfipc.com

::set dominio=www.redalyc.org

::PING -w 7500 %dominio% |find "TTL=" && ECHO dominio encontrado

::PING -w 7500 %dominio% |find "TTL=" || ECHO dominio no encontrado

::set servidor=148.215.24.111

::PING %servidor% -n 10
::ping google.com -f -l 1472

::ping google.com -f -l 576

::ping -n 1 ejemplo.com | find "TTL=" >> pingtest.txt

::echo .

::ping -n 16 127.0.0.1>nul

:: :START

:: SET CONNECT=SI

:: PING 72.14.204.147 | FIND "TTL=" > NUL

:: IF NOT ERRORLEVEL 1 GOTO SI

:: IF ERRORLEVEL 1 SET CONNECT=NO

:: ECHO %CONNECT% tienes conexion a internet en este momento

:: PING 1.1.1.1 -n 10 -w 30000 >NUL

:: CLS

:: GOTO START

:: pause>nul

:: EXIT

:: :SI

:: ECHO Estas conectado a internet

:: PING 1.1.1.1 -n 1 -w 30000 >NUL

:: CLS

:: GOTO START

:: pause>nul

::detener un comando

::echo Esperando 60 segundos...

::PING -w 10000 -n 1 1.1.1.1 > NUL

::echo OK ha transcurrido 1 minuto

::pause
::76 NET

::NET /?

::NET USER

::NET VIEW

::78 Ver DNS

ipconfig /displaydns

cmd.exe /k ipconfig /displaydns

::77.CHOICE

Choice /M "Quieres continuar?"

If Errorlevel 2 Goto No

If Errorlevel 1 Goto Yes

Goto End

:No

Echo Tu has elegido No

Goto End

:Yes

Echo Tu has elegido Si

:End
::79. doskey

echo Historial

doskey /history

::80.Apagar mquina

::SHUTDOWN /S /T 10 Apagar en 10 segundos.

::SHUTDOWN /S /P Apaga el equipo inmediatamente.

::SHUTDOWN /R /C "Se va a reiniciar el equipo para." Se inicia el apagado pero se muestra un


mensaje con el motivo.

::SHUTDOWN /R /T 10 /C "Reiniciando en 10 segundos" - Reinicia el equipo en 10 segundos y


muestra previamente un mensaje de advertencia.

::SHUTDOWN /I Abre una ventana de dialogo con distintas opciones para el apagado.

::SHUTDOWN /O /R /T 10 - Se reinicia el equipo en diez segundos, pero asegurando que se


muestren las opciones avanzadas de inicio.

::SHUTDOWN /H /F - Se hiberna el equipo y se cierran de forma forzada aplicaciones abiertas.

::Condicionar apagado

::ROBOCOPY G:/FILMS D:/FILMS /E & SHUTDOWN /S

::83. Rundll32

Opciones de internet

Abre en la ventana de Propiedades de Internet, la pestaa General

Rundll32 Shell32.dll, Control_RunDLL Inetcpl.cpl,,0

1 Seguridad

2 Privacidad

3 Contenido

4 Conexiones

5 Programas

6 Opciones avanzadas

7 General
Resolucin de pantalla

rundll32.exe shell32.dll,Control_RunDLL desk.cpl

Configuracin del protector de pantalla

rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,1

Personalizacin

rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,2

Opciones de energa

RunDll32.exe Shell32.dll,Control_RunDLL powercfg.cpl

Opciones de energa Configuracin avanzada

RunDll32.exe Shell32.dll,Control_RunDLL powercfg.cpl,,0

Region

Rundll32 Shell32.dll,Control_RunDLL Intl.cpl,,0

0 Formato

1 Ubicacin

2 Administrativo

Sonido

Rundll32 Shell32.dll,Control_RunDLL Mmsys.cpl,,0

0 Reproduccin

1 Grabar

2 Sonidos

3 Comunicaciones

Telfono y modem

rundll32.exe shell32.dll,Control_RunDLL telephon.cpl,,1

1 pestaa Modem

2 Opciones avanzadas

3 Reglas de marcado

Propiedades del teclado

RunDll32.exe shell32.dll,Control_RunDLL main.cpl @1

Propiedades del raton


RunDll32.exe shell32.dll,Control_RunDLL main.cpl @0

0,1 Punteros

0,2 Opciones de puntero

0,3 Rueda

0,4 Hardware

Dispositivos de juego

rundll32.exe shell32.dll,Control_RunDLL joy.cpl,,0

Quitar hardware de forma segura

RunDll32.exe shell32.dll,Control_RunDLL hotplug.dll

Fecha y hora

RunDll32.exe shell32.dll,Control_RunDLL timedate.cpl

Conexiones de red

RunDll32.exe shell32.dll,Control_RunDLL ncpa.cpl

Panel de Cuentas de usuario

RunDll32.exe shell32.dll,Control_RunDLL nusrmgr.cpl

Panel del Centro de actividades

RunDll32.exe shell32.dll,Control_RunDLL wscui.cpl

Firewall de Windows

RunDll32.exe shell32.dll,Control_RunDLL firewall.cpl

Lapiz y entrada tactil

rundll32.exe shell32.dll,Control_RunDLL tabletpc.cpl

Opciones de carpeta

RunDll32.exe shell32.dll,Options_RunDLL 0

0 General

2 Buscar

7 Ver

Propiedades de la barra de tareas

RunDll32.exe shell32.dll,Options_RunDLL 1
1 Barra de tareas

3 Lista de accesos directos

6 Barras de herramientas

Conectar a unidad de red

RunDll32.exe shell32.dll,SHHelpShortcuts_RunDLL Connect

Carpeta Impresoras

Rundll32 Shell32.dll,SHHelpShortcuts_RunDLL PrintersFolder

Carpeta de Fuentes del equipo

Rundll32 Shell32.dll,SHHelpShortcuts_RunDLL FontsFolder

Acerca de Windows

RunDll32.exe SHELL32.DLL,ShellAboutW

Hibernar el equipo

RunDll32.exe powrprof.dll,SetSuspendState

Administrador de dispositivos

RunDll32.exe devmgr.dll DeviceManager_Execute

Bloquear pantalla

RunDll32 user32.dll,LockWorkStation

Agregar ubicacin de red

rundll32.exe shwebsvc.dll,AddNetPlaceRunDll

Herramienta Asesor de contenido

RunDll32.exe msrating.dll,RatingSetupUI

Asistente para contrasea olvidada

RunDll32.exe keymgr.dll,PRShowSaveWizardExW

Organizar Favoritos de Internet Explorer

Rundll32.exe shdocvw.dll,DoOrganizeFavDlg

Interfaz de usuario de la impresora

Rundll32 Printui.dll,PrintUIEntry /?
::82. Rundll32

::Programas y caractersticas

::RunDll32.exe shell32.dll,Control_RunDLL appwiz.cpl,,0

::1 Instalar un programa desde la red

::2 Activar o desactivar caractersticas de Windows

::3 Configurar acceso y programas determinados del eq

::81. Rundll32

::Propiedades del sistema

::Rundll32 Shell32.dll,Control_RunDLL Sysdm.cpl,,1

::Sustituye el ltimo nmero por uno de los siguientes para abrir una pestaa diferente.

::1 Nombre del equipo

::2 Hardware

::3 Opciones avanzadas

::4 Proteccin del sistema

::5 Acceso remoto

::84.

:$reference https://www.facebook.com

set fecha=%date%

set hora=%time%

set u=%USERNAME%
title %USERDOMAIN%

Msg * "[ Fecha %fecha% , Hora: %hora% ] Hola %u% %c%"

::85. Comandos Batch

cls ::limpiar pantalla

ver ::ver version

date /t ::fecha

time /t ::hora

REM colocar titulo

title Comandos Batch

color 4f :: colocar color, 4 rojo, f blanco

del BatchInstall.bat ::borrar

::86. Find

find "El libro de los naufragios"


C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.txt

echo Introduce texto a buscar:

set /p buscar=

find "%buscar%" C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.txt

::87. Find

set archivo=C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.txt

echo Introduce texto a buscar:

set /p buscar=
IF EXIST %archivo% (

echo Existe archivo: %archivo%

find "%buscar%" %archivo%

find /i "%buscar%" %archivo%

find /i "%buscar%" %archivo%


C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST2.txt

) ELSE (

echo No existe archivo.

::88. Find

find /i "ateo" C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\*.txt

set archivo=C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\*.txt

echo Introduce texto a buscar:

set /p buscar=

IF EXIST %archivo% (

echo Existe archivo: %archivo%

find "%buscar%" %archivo%

find /i "%buscar%" %archivo%

find /i "%buscar%" %archivo% C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\*.txt

) ELSE (

echo No existe archivo.

::89. Find nmero de lneas


type C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.txt| find "ateo" /v /c

type C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.txt| find "abogado" /v /c

type C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.txt| find "Sartre" /v /c

type C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\*.txt| find "Sartre" /v /c

::90. Find nmero de lneas

set archivo=C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.txt

find /v /c "" %archivo%

echo ====================================

set archivo=C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\*.txt

find /v /c "" %archivo%

echo ************************************

::/v mostrar lneas que no contienen una cadena

find /v "" C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.txt

find /v "" C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST2.txt

echo ************************************

::/c mostrar lneas que contienen una cadena

find /c "" C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.txt

find /c "" C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST2.txt

echo ************************************

::/n mostrar nmero lneas

find /n "" C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.txt

find /n "" C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST2.txt

echo ************************************

::/i mostrar lneas que coinciden con cadena

find /i "ateo" C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST.txt

find /i "ateo" C:\Users\USUARIO\Desktop\ejemplosProg\utilidades\BOOKLIST2.txt


::0 Encontrado

::1 No encontrado

::2 Un parametro erroneo

::FIND [switch] "Cadena" rutaArchivo

::92.

FOR /L %i IN (1,1,254) DO ping -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txt

::91.FIND

echo Buscar Msg

FIND "Msg" *.bat

echo Buscar nslookup en archivos

FIND "nslookup" *.*

::93. Comandos de Red (http://whirlpool.net.au/wiki/windows_nw_diag_cmds)

::To display both the Ethernet statistics and the statistics for all protocols, type the following
command:

netstat -e -s

::To display the statistics for only the TCP and UDP protocols, type the following command:

netstat -s -p tcp udp

::To display active TCP connections and the process IDs every 5 seconds, type the following
command:
nbtstat -o 5

::To display active TCP connections and the process IDs using numerical form, type the following
command:

nbtstat -n -o

::pathping

pathping computerhope.com

getmac

ping -t www.facebook.com

::94. Comandos de Red (http://www.techrepublic.com/blog/10-things/10-windows-7-commands-


every-administrator-should-know/)

netstat /a

getmac

pathping computerhope.com

nbtstat -A 204.224.150.3

sfc /scannow

sigverif

driverquery

driverquery -v

driverquery -si

nslookup dc1.contoso.com

ping 192.168.1.1

pathping 192.168.1.1

ipconfig /all

::ipconfig /release

::ipconfig /renew

::ipconfig /flushdns

::repair-bde <source> <destination> -rk | rp <source>


::repair-bde c: d: -rk e:\recovery.bek

::repair-bde c: d: -rp 111111-111111-111111-111111-111111-111111

tasklist

tasklist -m

tasklist -svc

::taskkill -pid 4104

::taskkill -im iexplore.exe

::98. findstr

findstr /s "searchstring" *.txt

::97. Attrib; atributos de archivos

attrib -a -r -s -h \S \D *.*

::96. nmap

nmap -v -A www.google.com

::95. https://www.elhacker.net/comandos-protocolo-tcp-ip-windows.html

pathping www.dosprompt.info

ping www.dosprompt.info > c:\ping.txt

tracert www.dosprompt.info

tracert 85.234.131.90

nbtstat -A 148.215.24.39

nslookup elhacker.net 8.8.4.4

nslookup elhacker.net

netsh dump > fichero.dmp

netsh exec fichero.dmp


netstat -oa 148.215.24.15

ping -n 5 -l 1500 www.google.com

ping -a 192.168.1.22

fc archivo.txt archivo2.tx

arp -a

netstat -s

nbtstat -c

route print

ping www.redalyc.org -n 6

tracert -h 128 bad.horse

::100 net

echo messenger

set /p n=user/IP:

set /p M=Message:

net send %n% %M%

::99. msg send

echo Mandar mensaje

set /p n=User:

set /p m=Message:

msg send %n% %m%

::102 Redes

echo Abriendo conexiones de red

ncpa.cpl
::101 NET

::net /?

::net send ?

::net user

::net user USUARIO

::103. Comando ARP

arp -a

arp -g

arp -a -v

::104. GETMAC

GETMAC

GETMAC /?

GETMAC /FO csv

::105. NBTSTAT

NBTSTAT /?

NBTSTAT -a NADA -A 148.215.24.39

NBTSTAT -n

::106. NET

NET /?
NET user

NET view

NET localgroup

NET accounts

net view /all

::107. NETSTAT

NETSTAT /?

NETSTAT -p TCP

NETSTAT -p UDP

NETSTAT -p IP 148.215.24.33

netstat -sp ip ::for ipv4 statistics

netstat -sp ipv6 ::for ipv6 statistics

netstat -sp icmp ::for icmpv4 statistics

netstat -sp tcp ::for tcp statistics of IPv4

netstat -a

netstat -b

netstat -sp

netstat -r

::108 NETSH

NETSH /?

NETSH show

NETSH show helper

::109. NSLOOKUP
nslookup -q=ns microsoft.com a.root-servers.net

::110 PING

ping www.redalyc.org -w 6000

ping www.redalyc.org -n 14

ping 8.8.8.8

ping -t 148.215.24.111

::111 PING

:loop

ping 148.215.24.39 -l 65500 -w 1 -n 1

goto :loop

::112. https://stackoverflow.com/questions/13713318/ping-all-addresses-in-network-windows

FOR /L %%i IN (1,1,254) DO ping -n 1 192.168.10.%%i | FIND /i "Reply">>c:\ipaddresses.txt

FOR /L %%i IN (1,1,254) DO ping -a -n 1 192.168.10.%%i | FIND /i "Reply">>c:\ipaddresses.txt

FOR /L %%i IN (1,1,254) DO ping -a -n 1 192.168.10.%%i >>c:\ipaddresses.txt

::en consola:

::C:\Users\USUARIO\Desktop\ejemplosProg\utilidades>FOR /L %i IN (1,1,254) DO ping -n 1


192.168.10.%i >>ipaddresses.txt

::117

systeminfo
::117. http://tech-files.com/hack-wifi-password-using-cmd/

::netsh wlan show network mode=bssid ::mostrar wifi

::netsh wlan connect name=MyNet Algo ::conectarte

::netsh wlan disconnect ::desconectarte

::116. openfiles (http://blog.commandlinekungfu.com/)

openfiles /?

::115

::ping www.redalyc.org -t -l 65500

::114

::netsh wlan show profiles Chetansoni key=clear

::113. nmap

::nmap -A -v -sP -Pn 148.215.24.*

::121 obtener configuracin de grupo de trabajo en red

net config workstation

NBTSTAT -n

::120 netstat

for /L %%i in (1,1,9) do NETSTAT -b 148.215.24.%%i >> activas.txt


::119 nbtstat con for (conocer el grupo de trabajo en red)

for /L %%i in (1,1,254) do NBTSTAT -a 148.215.24.%%i >> workgroup.txt

::118 Conocer hostname (grupo de trabajo en red) remoto

nbtstat -a 148.215.24.9

::122 Ver dns

NSLOOKUP 148.214.24.9

for /L %%i in (1,1,254) do NSLOOKUP 148.215.24.%%i

::123 FINDSTR

FINDSTR "workgroup" temp.txt

FINDSTR "USUARIO" temp.txt

FINDSTR /B "USUARIO" temp.txt

FINDSTR /E "USUARIO" temp.txt

FINDSTR /L "USUARIO" temp.txt

FINDSTR /R "USUARIO" temp.txt

FINDSTR /S "USUARIO" temp.txt

FINDSTR /I "USUARIO" temp.txt

FINDSTR /X "USUARIO" temp.txt

FINDSTR /V "USUARIO" temp.txt

FINDSTR /N "USUARIO" temp.txt

FINDSTR /M "USUARIO" temp.txt

FINDSTR /O "USUARIO" temp.txt

FINDSTR /P "USUARIO" temp.txt


FINDSTR /S "USUARIO" *.txt

FINDSTR /x /c:"USUARIO" *.txt

::FINDSTR /n /i /c:"USUARIO" *

::124 FINDSTR

findstr /m "USUARIO" temp.txt

if %ERRORLEVEL%==0 (

msg * "Encontrado"

::125 FINDSTR

findstr /m "FER" temp.txt

if %ERRORLEVEL%==0 (

msg * "Encontrado"

) else (

msg * "No encontrado"

echo Contenido

type temp.txt

::128 TRACERT

for /L %%i in (1,1,254) do TRACERT 148.215.24.%%i

::127 PING

for /L %%i in (1,1,254) do PING -a -n 1 148.215.24.%%i


::127 NSLOOKUP

::en terminal:

::FOR %i IN (google.com facebook.com) DO nslookup %i

for /L %%i in (1,1,254) DO NSLOOKUP 148.215.24.%%i

for /L %%i in (google.com facebook.com redalyc.org javamexico.org) DO NSLOOKUP %%i

::126 NETSTAT

for /L %%i in (1,1,254) do NETSTAT -a 148.215.24.%%i

::129. Prueba de IF (source:https://community.spiceworks.com/topic/2010184-how-to-test-a-set-


of-conditions-with-if-windows-batch)

:: - Impossible Label to Jump to but far faster than REM but has the same impact

find /i "%computername%" "exclusions.txt" > NUL

if ErrorLevel==2 goto _missingInputFile

if ErrorLevel==1 goto _serverNotInFile

goto _end

:_serverNotInFile

:: --- here are the installation instructions

echo No encontrado

goto _end

:_missingInputFile

:: This line is always good to insert. This way if you add a label between here and the _end you're
covered
goto _end

:_end

echo Fin

::131 info del sistema,https://norfipc.com/comandos/informacion-pc-uso-wmic.html

::(https://norfipc.com/comandos/informacion-pc-uso-wmic.html)

WMIC /Output:STDOUT BIOS get /all /format:LIST

::Toda la Informacin sobre tu CPU

WMIC /Output:STDOUT CPU get /all /format:LIST

::Toda la Informacin sobre tu CDROM

WMIC /Output:STDOUT CDROM get /all /format:LIST

::Toda la Informacin sobre REDES

WMIC /Output:STDOUT NICCONFIG get /all /format:LIST

::Toda la Informacin sobre tu sistema

WMIC /Output:STDOUT COMPUTERSYSTEM get /all /format:LIST

::Toda la Informacin sobre tus discos

WMIC /Output:STDOUT DISKDRIVE get /all /format:LIST

::Toda la Informacin sobre discos logicos

WMIC /Output:STDOUT LOGICALDISK get /all /format:LIST

::Toda la Informacin sobre tu memoria

WMIC /Output:STDOUT MEMPHYSICAL get /all /format:LIST

::Toda la Informacin sobre los servicios

WMIC /Output:STDOUT SERVICE get /all /format:LIST

::Toda la Informacin sobre los procesos

WMIC /Output:STDOUT PROCESS get /all /format:LIST

::Toda la Informacin sobre los programas en el inicio de Windows


WMIC /Output:STDOUT STARTUP get /all /format:LIST

::Toda la Informacin sobre los dispositivos en tu motherboard

WMIC /Output:STDOUT ONBOARDDEVICE get /all /format:LIST

::Toda la Informacin sobre errores del sistema operativo

WMIC /Output:STDOUT RECOVEROS get /all /format:LIST

::Lista de procesos incubados en svchost.exe:

wmic process where (Name='svchost.exe') get name, processid, commandline

::Cambiar la prioridad de una aplicacin:

wmic process where name="explorer.exe" call setpriority 64

::Comenzar una aplicacin:

wmic process call create "notepad.exe"

::Terminar una aplicacion:

wmic process where name="notepad.exe" call terminate

::Administrar servicios:

wmic service where caption="DHCP Client" call changestartmode "Disabled"

::Habilitar direccin IP dinmica:

wmic nicconfig where index=9 call enabledhcp

::Establecer direccin IP esttica:

wmic nicconfig where index=9 call enablestatic("192.168.16.4"), ("255.255.255.0")

::130. Ver interrfaces de red

netsh interface show interface

::132 WMIC, System, BIOS, Motherboard, source:


http://programming.realworldrobotics.com/editors-ides/command-line-in-windows/wmic-
snippets

wmic computersystem get domain, EnableDaylightSavingsTime, Manufacturer, Model,


PartOfDomain, TotalPhysicalMemory, username
wmic bios get Caption, Manufacturer, SMBIOSBIOSVersion, Version

wmic baseboard get Manufacturer, Model, Product, SerialNumber, Version

::133 Processor Info ,source: http://programming.realworldrobotics.com/editors-ides/command-


line-in-windows/wmic-snippets

wmic cpu get deviceID, Addresswidth, MaxClockSpeed, Name, Manufacturer, ProcessorID

::134 Hard Drives ,source: http://programming.realworldrobotics.com/editors-ides/command-


line-in-windows/wmic-snippets

wmic logicaldisk where drivetype=3 get name, freespace, systemname, filesystem, size,
volumeserialnumber

::135. Memoria, source:http://programming.realworldrobotics.com/editors-ides/command-line-


in-windows/wmic-snippets

wmic memlogical get AvailableVirtualMemory, TotalPhysicalMemory, TotalVirtualMemory

::136 Impresoras, source:http://programming.realworldrobotics.com/editors-ides/command-line-


in-windows/wmic-snippets

wmic printer get Caption, Default, Direct, Description, Local, Shared, Sharename, Status

::137. Users and Groups, source:http://programming.realworldrobotics.com/editors-


ides/command-line-in-windows/wmic-snippets

wmic useraccount where "LocalAccount='TRUE'" get Caption, Disabled, Domain, Lockout,


PasswordExpires, SID, Status

wmic group where "LocalAccount='TRUE'" get Caption, SID, Status


::139 BIOS

WMIC /Output:lista.html BIOS get /all /format:htable

::138 Query remote hosts, source: http://programming.realworldrobotics.com/editors-


ides/command-line-in-windows/wmic-snippets

wmic /node:fs1 /user:mydomain\quuxadmin /password:mypass logicaldisk where drivetype=3 get


name, freespace, filesystem, size

::140. WINSAT

WINSAT FORMAL

WINSAT QUERY

::141 WMIC

WMIC /Output:lista.txt diskdrive get status

::143.WINSAT

WINSAT FEATURES

WINSAT FORMAL

WINSAT QUERY

WINSAT DISK

WINSAT MEM

WINSAT DWM

WINSAT CPUFORMAL

WINSAT GRAPHICSFORMAL
WINSAT D3D

WINSAT MFMEDIA

WINSAT MEM -XML lista.xml

WINSAT GRAPHICSFORMAL -XML lista.xml

::142 WMIC

::Toda la Informacin sobre tu BIOS

WMIC /Output:lista.html BIOS get /all /format:htable

::Toda la Informacin sobre tu CPU

WMIC /Output:lista.html CPU get /all /format:htable

::Toda la Informacin sobre tu CPU

WMIC /Output:lista.html CPU get /all /format:LIST

::Toda la Informacin sobre tu CDROM

WMIC /Output:lista.html CDROM get /all /format:LIST

::Toda la Informacin sobre REDES

WMIC /Output:lista.html NICCONFIG get /all /format:LIST

::Toda la Informacin sobre tu sistema

WMIC /Output:lista.html COMPUTERSYSTEM get /all /format:LIST

::Toda la Informacin sobre tus discos

WMIC /Output:lista.html DISKDRIVE get /all /format:LIST

::Toda la Informacin sobre discos logicos

WMIC /Output:STDOUT LOGICALDISK get /all /format:LIST

::Toda la Informacin sobre tu memoria

WMIC /Output:lista.html MEMPHYSICAL get /all /format:LIST

::Toda la Informacin sobre los servicios

WMIC /Output:lista.html SERVICE get /all /format:LIST

::Toda la Informacin sobre los procesos

WMIC /Output:lista.html PROCESS get /all /format:LIST


::Toda la Informacin sobre los programas en el inicio de Windows

WMIC /Output:lista.html STARTUP get /all /format:LIST

::Toda la Informacin sobre los dispositivos en tu motherboard

WMIC /Output:lista.html ONBOARDDEVICE get /all /format:LIST

::Toda la Informacin sobre errores del sistema operativo

WMIC /Output:lista.html RECOVEROS get /all /format:LIST

::Lista de procesos incubados en svchost.exe:

wmic process where (Name='svchost.exe') get name, processid, commandline

::Cambiar la prioridad de una aplicacin:

wmic process where name="explorer.exe" call setpriority 64

::Comenzar una aplicacin:

wmic process call create "notepad.exe"

::Terminar una aplicacion:

wmic process where name="notepad.exe" call terminate

::Administrar servicios:

wmic service where caption="DHCP Client" call changestartmode "Disabled"

::Habilitar direccin IP dinmica:

wmic nicconfig where index=9 call enabledhcp

::Establecer direccin IP esttica:

wmic nicconfig where index=9 call enablestatic("192.168.16.4"), ("255.255.255.0")

::144.

set/p num1=Cual es el primer numero?

set/p num2=Cual es el segundo numero?

set/a media= (%num1% + %num2%) / 2


echo.

echo La media es %media%

:principio

set/p cant=Entre cuantos numeros quiere hacer la media?

set/a contador=%cant%

set total=0

if %cant% LSS 2 (goto mal) else (goto pregunta)

:mal

echo Debe indicar un numero mayor o igual que 2

goto principio

:pregunta

set/p num=Escriba uno de los %cant% numeros

set/a total=%total%+%num%

set/a contador=%contador%-1

if not %contador% == 0 (goto pregunta)

set/a media= %total% / %cant%

echo.

echo La media es %media%

set/p uno=Escriba el numerador

:denominador

set/p dos=Escriba el denominador

if %dos%==0 (goto nosepuede) else (goto dividir)

:nosepuede

echo El denominador no puede ser cero.

goto denominador
:dividir

set/a tres=%uno%/%dos%

echo El resultado de %uno%/%dos% es %tres%

pause>nul

exit

::pause >nul

::exit

::145

set a=%1

set b=%2

echo Hola %a% %b%

::146. Windows 8

::Salida con htable (http://waynes-world-it.blogspot.mx/2008/07/wmic-custom-alias-and-


format.html)

WMIC /Output:lista.html LOGICALDISK get /all /format:htable

wmic process list /format:htable:"sortby=Name" >> lista.html

WMIC BIOS get /all /format:htable >> lista.html

WMIC CPU get /all /format:htable >> lista.html

WMIC CDROM get /all /format:htable >> lista.html

WMIC NICCONFIG get /all /format:htable >> lista.html

WMIC COMPUTERSYSTEM get /all /format:htable >> lista.html

WMIC DISKDRIVE get /all /format:htable >> lista.html

::147. source: http://waynes-world-it.blogspot.mx/2008/07/wmic-custom-alias-and-format.html

::Use WMIC to get instances of a class and format the output as CSV
wmic path win32_process get name,commandline /format:csv

::Use WMIC aliases to format the output in CSV or XML

wmic process list /format:xml

wmic process list /format:csv

::Use WMIC aliases to format the output in HTML TABLE, MOFCSV or XML

wmic process list /format:htable

wmic process list /format:HMOF

::Use WMIC aliases to sort the output in HTML

wmic process list /format:htable:"sortby=Name" > test.html

::Use WMIC aliases to filter and sort the output in CSV

wmic process get name /format:csv:"datatype=text":"sortby=Name"

::Use WMIC remotely aliases to retrieve command-line process arugments

wmic /node:"%server%" process get name,CommandLine /format:csv:"sortby=Name"

::Use WMIC wmic aliases to sort the result set by number

wmic Logon get /Format:htable:"datatype=number":"sortby=LogonType"

::Use a custom WMIC alias to report printer info from a cluster node in CSV

wmic /node:"%server%" spoolerjobs list /format:table

::Use a custom WMIC alias to report sorted HTML printer info from a cluster node

wmic /node:"%server%" spoolerjobs list


/format:htable:"datatype=number":"sortby=TotalJobsPrinted"

::Use a custom WMIC alias to report a brief summary of printer statistics


wmic /node:"%server%" spoolerjobs list brief
/format:htable:"datatype=number":"sortby=TotalJobsPrinted"

::Use a custom WMIC alias and xsl to sort print jobs output descending HTML table

wmic /node:"%server%" spoolerjobs list brief /format:"htabledesc-


sortby.xsl":"datatype=number":"orderby=descending":"sortby=TotalJobsPrinted" > test.html

::Query a user from AD using WMI

wmic /node:"%DC%" /namespace:\\root\directory\LDAP path ds_user where


"ds_cn='%username%'" GET
ds_displayName,DS_UserPrincipalName,ds_cn,ds_name,ds_whenCreated

::51. Windows 8

hostname

::148.

del lista.html

WMIC process list /format:htable > lista.html

WMIC BIOS get /all /format:htable >> lista.html

wmic computersystem list full /format:htable >> lista.html

wmic process list /format:htable >> lista.html

wmic ntdomain list /format:htable >> lista.html

wmic useraccount list /format:htable >> lista.html

wmic group list /format:htable >> lista.html

wmic sysaccount list /format:htable >> lista.html

wmic csproduct get vendor,name,identifyingnumber /format:htable >> lista.html

::150. ejecutar aplicacion


::wmic process call create "calc.exe"

::152 Ver impresora(s)

wmic /node:EquipoMiFerCarraro printer list status

wmic /node:EquipoMiFerCarraro printer list status /format:htable > impresoras.html

::153. WMIC

::Entrar:

wmic

::Saber la asociacion con el OS:

os assoc

::Conocer oppciones de Desktop

desktop /?

::Conocer oppciones del cd:

cdrom /?

::Interfaces de red:

nic list

::Procesos:

process get name,processid

process where processid="1000" call terminate

::desde una mquina remota:

/node:localhost/IP /user:USER /password:123456 process where name="paint.exe" call terminate

::salir:

quit
::pause

:EndComment

::63. comentarios multi lnea

GOTO Comentario

echo esto no se ve, es un comentario multilinea

:Comentario

You might also like