-1

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)
Compo
  • 36,585
  • 5
  • 27
  • 39

1 Answers1

0

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
Compo
  • 36,585
  • 5
  • 27
  • 39
  • Thank you so much, that's exactly what I was trying to do. Just one more thing. I've edited the code to actually display when an error is thrown (as that's how I know if the computer is offline that it's trying to connect to), but it displays in a very weird format, usually like this: `Node - COMPUTERNAME ERROR: Description = The RPC server is unavailable` Is there a way to edit it so that it just says something like "Machine Name: NAME is offline."? – TheWindBlows Mar 08 '18 at 00:19
  • You said you'd 'edited the code to actually display when an error is thrown'. Unless I'm mistaken all you've done is change the strings, `Machine Name` and `Last Login` to `Host` and `Username` respectively and output to a text file. BTW, the `2^>Nul` supresses errors from the `WMIC` command, removing it or filtering the errorlevel may provide you with a solution to your new request. Please remember though that your question as asked has been adequately answered by my answer; asking for additional things after the responses becomes a new question. – Compo Mar 08 '18 at 10:14