问题
For asset stocktake purposes, I'm trying to create a script in batch that runs through the machine names of computers which are in a local .txt file, getting the last person who logged into the machine, and outputting that to a text file with the format of Machine Name: NAME | Last Login: USER
I've hit a bit of a wall and I can't figure out what's going on. The machine name is being correctly output but the 'last login' part is not. Here is my code:
@echo off
for /f %%a in (Assets.txt) do (
for /f %%b in ('wmic.exe /node:"%%a" computersystem get username') do set lastlogin=%%b
echo Machine Name: %%a Last Login: %lastlogin%)
pause
Any help would be greatly appreciated. Thank you.
Update 2
for /f "delims=" %%a in (Assets.txt) do (
for /f "skip=1 delims=" %%b in (
'WMIC /Node:"%%a" ComputerSystem Get UserName 2^>nul'
) do for %%c in (%%b) do echo Host: %%a Username: %%b >>Usernames.txt)
回答1:
There really shouldn't be any need to set variables and therefore no need to enable delayed expansion.
You may be able to change your script to something like this:
@Echo Off
For /F "Delims=" %%A In (Assets.txt) Do (
For /F "Skip=1 Delims=" %%B In (
'WMIC /Node:"%%A" ComputerSystem Get UserName 2^>Nul'
) Do For %%C In (%%B) Do Echo Machine Name: %%A Last Login: %%B)
Pause
You may be able to so it like this too:
@Echo Off
For /F "Skip=1 Delims=" %%A In ('
"WMIC /Node:@Assets.txt ComputerSystem Get Name, UserName"
') Do Call :Sub %%A
Pause
Exit /B
:Sub
If Not "%1"=="" Echo Machine Name: %1 Last Login: %2
来源:https://stackoverflow.com/questions/49144222/defined-variable-not-outputting-in-batch-script