【问题标题】:How to enable and disable network connection when connection to interntet is dropped while everything is logged?在记录所有内容时断开与互联网的连接时如何启用和禁用网络连接?
【发布时间】:2015-08-18 15:26:20
【问题描述】:

我正在尝试在 Batch、Powershell (Win8.1) 或 Python(3.4) 中创建一个脚本。该脚本将每 15 分钟左右循环一次,测试互联网连接是否仍然存在。如果连接处于活动状态,则脚本将打印带有时间戳的 Pass 并保存到日志文件中。如果 Internet 连接断开或断开,则脚本将在记录时间和测试结果时禁用并重新启用网络适配器。我想我已经缩小了一个非常可靠的批处理文件的范围。

我遇到的问题是,当我以允许执行 powershell 命令的管理员权限运行脚本时,日志文件没有更新。当我在没有管理员权限的情况下运行批处理文件时,日志文件会更新,但 powershell 命令不起作用。

我也尝试过使用命令行代码代替 powershell 命令的相同脚本,我只是觉得 Powershell 更快:

netsh interface set interface "Ethernet" DISABLED
netsh interface set interface "Ethernet" ENABLED

到目前为止我的代码:

@setlocal enableextensions enabledelayedexpansion
@echo off

rem Google DNS Most reliable IP for ping testing.
set ip=8.8.8.8

:retest
cls
echo.
echo %TIME%: Testing Internet Connection...

ping -n 1 %ip% | find "TTL"
if not errorlevel 1 set error=Pass
if errorlevel 1 set error=Fail
echo.
echo Time: %TIME% Result: %error%
echo Time: %TIME% Result: %error% >> Server_Restarts.log
echo.
goto %error%

:Pass
echo Retest in 15 minutes..
timeout /T 900 /NOBREAK
goto retest

:Fail
echo Restarting Network..
echo Connection Failed at %TIME%.. >> Server_Restarts.log
timeout /t 5 /nobreak
echo. >> Server_Restarts.log
echo.
echo Restarting Network at Date: %DATE% and Time:%TIME%..
echo Restarting Network at Date: %DATE% and Time:%TIME%.. >> Server_Restarts.log
echo %TIME% Disabling Network Connection..
Powershell.exe Disable-NetAdapter -Name * -Confirm:$false
echo %TIME% Enabling Network Connection..
Powershell.exe Enable-NetAdapter -Name "Ethernet"
echo Network Connection Reset at %TIME%..
echo Network Connection Reset at Date: %DATE% and Time:%TIME%.. >> Server_Restarts.log
echo. >> Server_Restarts.log
timeout /t 5 /nobreak
goto retest

【问题讨论】:

  • 你怎么知道它不会写入你的文件?您使用的是相对路径,因此位置可能不同。如果您右键单击并使用“以管理员身份运行”,它会将文件保存在c:\windows\system32\Server_Restarts.log
  • 哦不..你说的太对了,我现在感觉很傻..:(我不知道为什么我没有想到这一点。你是一个救生员。

标签: windows powershell batch-file


【解决方案1】:

您使用的是相对路径,因此位置可能不同。如果您右键单击并使用“以管理员身份运行”,它会将文件保存在c:\windows\system32\Server_Restarts.log 中。使用日志文件的绝对路径或保存在与批处理文件相同的目录中,如下所示:

Time:%TIME%.. >> "%~dp0Server_Restarts.log"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-27
    • 2017-05-02
    • 1970-01-01
    • 2013-10-26
    • 2016-01-19
    • 2016-05-07
    • 2018-01-09
    • 1970-01-01
    相关资源
    最近更新 更多