简体   繁体   中英

Network Adapter Batch Identification

I am attempting to create a batch script that will allow for the identification of the network connections (Updated).

This is a much simpler version than what I had before, however running into issues when calling the if statement.

@echo off
wmic nic get NetConnectionID, NetConnectionStatus
set Connection=(wmic path Win32_NetworkAdapter Where AdapterTypeID=0)
set Status=(wmic path Win32_NetworkAdapter Where NetConnectionStatus=2)

IF %Connection% and %Status% ( 
echo %computername% is connected to the network via Ethernet Wired/Wireless
Pause
::exit /b 2 
) ELSE (
echo %computername% is not connected to a Network
Pause
::exit /b 1
)

You can only set the result of a command to a variable by using a for /f loop. For example, %Connection% would be set like this:

for /f %%A in ('wmic path Win32_NetworkAdapter Where AdapterTypeID=0') do set Connection=%%A


HOWEVER
If you look at the actual output of wmic path Win32_NetworkAdapter Where AdapterTypeID=0 , you'll see that there is way too much data in there for your variable to be useful. Additionally, you can combine your two wmic queries into one, eliminating the need for an if statement altogether.

echo The following computers are connected to the network via Ethernet/Wireless:
wmic path Win32_NetworkAdapter where "AdapterTypeId=0 and NetConnectionStatus=2" get SystemName
pause

If you only want to return an errorlevel based on whether or not any are actually found, you have to redirect STDERR to STDOUT and then look for the string that gets returned when no instance is found. This means that the script returns 1 if it finds any connected computers and 0 if it does not (this is the opposite of normal errorlevel values).

wmic path Win32_NetworkAdapter where "AdapterTypeId=0 and NetConnectionStatus=2" 2>&1|find "No Instance"
echo %errorlevel%

It's also worth noting that batch doesn't have support for logic in if statements, so you can only simulate and s by nesting if s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM