- ¿Por qué?

- ¿Por qué?

He escrito la solución sugerida enRegistrar la salida de un archivo por lotes completo.

Pero solo funciona cuando el script por lotes no solicita acceso de administrador ni acepta ninguna entrada del usuario.

En mi script, tengo acceso administrativo y también tengo entrada del usuario:

@echo off
:: BatchGotAdmin
::-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"="
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
::--------------------------------------
set LOGFILE=batch.log
call :LOG > %LOGFILE%
exit /B
:LOG
REM Set IP address to USB Ethernet
echo "Set IP address to USB Ethernet :"
set /p SystemIP="Enter the System IP address[127.*.*.*]:" 
set /p  SystemSubnetMask="Enter the System Subnetmark[Default:255.255.255.0]:" 
IF [%system_subnetmask%]==[] set /p system_subnetmask=255.255.255.0
set /p SystemGateway="Enter the System Default Gateway[127.*.*.*]:" 
echo "Aviliable Ethernet Interface :"
netsh interface show interface
set /p EthernetInterfaceName="Type the Ethernet Interface Name:" 
netsh interface ip set address %EthernetInterfaceName% static %SystemIP% %SystemSubnetMask% %SystemGateway%
netsh interface ip set dns %EthernetInterfaceName% static 8.8.8.8
netsh interface ip add dnsserver %EthernetInterfaceName% address=4.2.2.2 index=1

Respuesta1

"¿Cómo realizar el registro después de obtener acceso de admisión en un script por lotes?"

  • Elenlaceen su pregunta responde esto de una amplia variedad de maneras.

"He escrito la solución sugerida en el siguiente enlace, pero solo funciona cuando el script por lotes no solicita acceso de administrador...

  • Algunos cambios/ediciones en su código son necesarios, incluidos aquellos que hacen uso de, y que interfieren con la mecánica de solicitar derechos de administrador".

"... o tomar cualquier entrada del usuario."

  • Estas acciones en tu código, que recibirán entradas, son posteriores a la acción de obtener derechos de administrador (por VBS), por lo que si no ocurre la anterior, esta tampoco ocurre.

Sin entrar en mucho detalle, tu objetivo se centra en obtener los logs de las ejecuciones de tus comandos listados por lotes, pero al intentar esto estás omitiendo las salidas de la pantalla porque utilizas la redirección a un archivo de log, sin embargo, sin darte cuenta. que la pantalla (stdout) no tendrá ninguna salida de comando, incluso se paralizará y esperará las set /pentradas de comando.

Esto no interrumpe exactamente el código en ejecución, pero ciertamente se "cuelga" sin mostrar ningún mensaje en la pantalla y permanece allí esperando que continúe la interacción usuario/administrador, lo que nunca sucede.


Lo que sugiero entonces serían cambios en los que las acciones necesarias para el registro se dividieran de las acciones necesarias para recibir interacción/aporte:

@echo off

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" && goto :gotAdmin

echo/Requesting administrative privileges... & goto :UACPrompt
 
:UACPrompt 
set "_params=" & if not "%*" == "" =;(
     set "_params=%*" 
     call set "_params=%%_params:"=%%"
    );=
    
> "%temp%\getadmin.vbs" =;(
     echo/Set UAC = CreateObject("Shell.Application"^)
     echo/UAC.ShellExecute "%ComSpec%", "/c %~s0 %_params%", "", "runas", 1
    );= && "C:\Windows\System32\cscript.exe" //Nologo "%temp%\getadmin.vbs" 

>nul 2>&1 del /q "%temp%\getadmin.vbs" & exit /b || goto :eOf

:gotAdmin
cd /d "%~dp0"
set "_LogFile=%temp%\batch.log"

echo/Set IP address to USB Ethernet : 
set /p "_SystemIP=Enter the System IP address [127.*.*.*]: " 
set /p "_SystemSubnetMask=Enter the System Subnet Mask [Default: 255.255.255.0]: "

if "%_SystemSubnetMask%" == "" set "_System_SubnetMask=255.255.255.0"
set /p "_SystemGateway=Enter the System Default Gateway [127.*.*.*]: " 

echo/Aviliable Ethernet Interface:
"C:\Windows\System32\netsh.exe" interface show interface | findstr .

set /p "_EthernetInterfaceName=Type the Ethernet Interface Name: " 

:: logging commands after defined in/with admin inputs
:: ----------------------------------------------------
for %%i in (EthernetInterfaceName,SystemIP, SystemSubnetMask, SystemGateway
    )do "%ComSpec%" /v:on /e:on /c "echo/%%~i: !_%%~i!"

2>&1 =;(
      netsh interface show interface | findstr .
      for %%i in (EthernetInterfaceName,SystemIP, SystemSubnetMask, SystemGateway)do "%ComSpec%" /v:on /e:on /c "echo/%%~i: !_%%~i!"
      echo\ "C:\Windows\System32\netsh.exe" interface ip set address %_EthernetInterfaceName% static %_SystemIP% %_SystemSubnetMask% %_SystemGateway%
      echo\ "C:\Windows\System32\netsh.exe" interface ip set dns %_EthernetInterfaceName% static 8.8.8.8
      echo\ "C:\Windows\System32\netsh.exe" interface ip add dnsserver %_EthernetInterfaceName% address=4.2.2.2 index=1
      echo\ "C:\Windows\System32\ipconfig.exe" /flushdns
     );= >"%_LogFile%"

type "%_LogFile%" | clip 
"C:\Windows\System32\timeout.exe" -1

- ¿Por qué?

Aunque es posible redirigirstderrastdout, también es posible redirigirstderrystdoutsimultáneamente lo que no es posible es redirigirstdin(set /P)astdouta un archivo y simultáneamente tenerstdouten pantalla recibiendostdin. Y tu pregunta apunta a ese objetivo.


Flujo de puntero

Los punteros constantes globales stdin, stdout y stderr son flujos estándar para entrada, salida y salida de error.

stdin  Standard input     
stderr Standard error 
stdout Standard output

Redirection:
stderr  <to>  Null      <use>  2>Nul
stderr  <to>  stdout    <use>  2>&1 
stderr  <to>  File.Log  <use>  2>File.Log

stdout  <to>  Null      <use>  >Nul
stdout  <to>  Null      <use> 1>Nul
stdout  <to>  File.Log  <use>  >File.Log
stdout  <to>  File.Log  <use> 1>File.Log

Redirection stdout and stderr to File.Log:
2>&1  YourCommandHere   >File.Log
2>&1  YourCommandHere  1>File.Log

Set IP address to USB Ethernet : 
Enter the System IP address [127.*.*.*]:               //user input [stdin]
Enter the System Subnet Mask [Default: 255.255.255.0]: //user input [stdin]
Enter the System Default Gateway [127.*.*.*]:          //user input [stdin]
Avaliable Ethernet Interface:
Admin State.    State         Type            Interface Name
-------------------------------------------------------------------------
Enable          Conected      Dedicaed        Wi-Fi
    
Type the Ethernet Interface Name:                      //user input [stdin]

Recursos adicionales:

información relacionada