开发者

Windows: Obtaining and Storing a Machine Name in a Variable

开发者 https://www.devze.com 2023-02-02 12:32 出处:网络
I have a script that is run over a network, with VPN being the same as a LAN environment. The script previously worked fine, as we had variables that stored the username and password for the adminis

I have a script that is run over a network, with VPN being the same as a LAN environment.

The script previously worked fine, as we had variables that stored the username and password for the administrator. However, due to a recent change, when we map a drive over the network and whatnot, the machine name is now needed in front of the administator username, E.g. machinename2343\administrator.

What I would like to do is take an existing command - perhaps such as nbtstat - and after entering the ip address, have the program pull the machine name and insert it into a variable.

I have found that Nbtstat can give me the machine name, but provides large amounts of unnecessary information for my task. Is there a way to filter out just the machine name in a reliable and consistent manner, or is there perhaps another network related command that perform in the same capacity?

`@echo off

FOR /f "tokens=1* delims= skip=23 " %%a IN ('nbtstat -a IPADDRESS) DO ( SET VARIABLE=%%a GOTO Don开发者_如何转开发e ) :Done echo Computer name: %VARIABLE%`


You could do ping /a. The computer name is resolved. And this computer name is the second token. I haven't taken care of Error checking. I believe you could implement that yourself. Try this:

@ECHO OFF
FOR /f "tokens=2* delims= " %%a IN ('PING -a -n 1 IPADDRESS') DO (
    SET Variable=%%a
    GOTO Done
)
:Done
echo Computer name: %Variable%

Put this in your batch file where it would fit.


You could just use the %computername% environment variable.

When I first read your post I thought you were running the batch file remotely on each machine. If that were the case having %computername% in the batch file would work, because when the batch file is executed remotely %computername% would be expanded based on the remote machine's environment variable not the local machine.

Looking back on it, it's still not very clear, but based on your comment I assume the batch file is running locally and then connecting to a set of machines to perform some operation(s).

You could use tool the WMI command-line tool to get the computer name. The solution would look similar to @Thrustmaster's, but I think it's a little cleaner since the output of wmic, in this case, does "filter out just the machine name in a reliable consistent manner." Of course you'd replace the 127.0.0.1 with the ip you want to query.

@ECHO OFF
FOR /F "tokens=*" %%A IN ('wmic /node:127.0.0.1 ComputerSystem Get Name /Value ^| FIND "="') DO (
    SET COMP.%%A
)
ECHO %COMP.NAME%
0

精彩评论

暂无评论...
验证码 换一张
取 消