批处理文件IF条件

问题描述

我正在尝试使用以下代码与netsh(我宁愿不使用wmic)建立当前的活动连接。

@echo off

FOR /F "tokens=3,*" %%A IN ('netsh interface show interface^|findstr /i "\<connected\>"') DO (

if %%B == .........
)

我只想考虑默认的连接名称:

Wi-Fi,以太网,无线网络连接,本地连接,并基于此进行操作。

例如:如果%% B = WiFi或以太网或....(

::在这里做点什么 )

我只希望“某事”执行一次,因为在任何给定时间只有其中一个连接处于活动状态。

解决方法

我认为应该采取以下措施:

@echo off

SETLOCAL ENABLEDELAYEDEXPANSION

for /f "tokens=3,*" %%a in ('netsh interface show interface ^| findstr /i "\<connected\>"') do (
    set ifname=%%b
    if "!ifname:~0,8!"=="Ethernet" goto execute
    if "!ifname:~0,21!"=="Local Area Connection" goto execute
    if "!ifname:~0,5!"=="Wi-Fi" goto execute
    if "!ifname:~0,27!"=="Wireless Network Connection" goto execute
)
echo No connected interface found,exiting...
goto :EOF

:execute
echo Found connected interface (%ifname%),executing...
:: do whatever you need

基本上,这个想法是寻找以这四个不同的字符串开头的接口,然后跳转到执行所需内容的标签。

[如果我不指出现在最好在PowerShell中执行此操作,我会很失落,但是…]

,

这是一个未经测试的示例,应该告诉您与您唯一分配的IP地址关联的设备的接口名称。

@Echo Off
SetLocal EnableExtensions
For /F "Delims==" %%G In ('"(Set Interface) 2> NUL"') Do Set "%%G="
For /F Tokens^=4 %%G In ('%__APPDIR__%ROUTE.EXE -4 PRINT 0.0.0.0 ^
 ^| %__APPDIR__%findstr.exe /RC:"0.0.0.0 *0.0.0.0"') Do (Set "InterfaceIP=%%G"
    For /F Tokens^=5* %%H In ('%__APPDIR__%netsh.exe interface IP show route^
 ^|%__APPDIR__%find.exe "%%G"') Do Set "InterfaceName=%%I")
If Not Defined InterfaceIP GoTo :EOF
Set Interface & Pause

[编辑/]

这是我的注释示例的略微修改版本,它使用ping.exe而不是ROUTE.EXE返回用于确定接口名称的IP地址。

@Echo Off
SetLocal EnableExtensions
For /F "Delims==" %%G In ('"(Set Interface) 2> NUL"') Do Set "%%G="
For /F "Tokens=2 Delims=[]" %%G In ('^"%__APPDIR__%ping.exe "%COMPUTERNAME%" ^
 -n 1 -4 2^> NUL ^| %__APPDIR__%find.exe /I "%COMPUTERNAME%"^"') Do (
    Set "InterfaceIP=%%G" & For /F Tokens^=5* %%H In ('%__APPDIR__%netsh.exe ^
     interface IP show route ^| %__APPDIR__%find.exe "%%G"'
    ) Do Set "InterfaceName=%%I")
If Not Defined InterfaceIP GoTo :EOF
Set Interface & Pause

两个示例的最后一行仅显示两个变量,以便您可以看到它们。显然,您将用其余的代码替换这些代码。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...