我的目标是制作一个通用代码,循环遍历计算机中的所有用户帐户名称并将输出发送到批处理文件。 “net user”命令输出用户列表,但我想将每个用户名分配给一个参数。所以我应该使用for /f
命令去做。这可能看起来很简单,但请记住用户名可能在任何位置包含空格:开头、结尾或中间,此外,还可以找到 2 个连续的空格
提示1:用户名的最大长度为20个字符
提示 2:循环需要遍历错误的用户名,因此需要检查它们是否有效。命令net user "uName"
sets %ErrorLevel%
如果用户名“uName”(例如)有效,则为 0。
如果没有办法,也许 VBScript 可以使用每个用户帐户名启动批处理文件。
Edit:我终于编写了自己的代码,但是只需要15个帐户就需要大约5秒。
我想要一个更好的解决方案,也许使用另一种编程语言。
setlocal EnableDelayedExpansion
For /f "skip=4 delims=" %%I in ('net user') do (
Set "Line=%%I"
If not "!Line:~-1,1!" == "." for %%I in (0,25,50) do (
Set "Name=!Line:~%%I,20!"
Call :setName
)
)
Set Name=
:setName
If not "!Name!" == "" (
Net user "!Name!" && %~dp0Test.bat "!Name!"
If not "!Name:~-1,1!" == " " goto:eof
Set "Name=!Name:~0,-1!"
Goto setName
)
endlocal
根据我的测试,名称开头或结尾带有空格的用户帐户名是不可能的。用户帐户名称中的非空白字符之间只能有空格。
这是我评论的批处理解决方案,它也不是很快。
@echo off
rem Process output of command 'net user' line by line with skipping
rem the first 4 lines and stopping processing when line with success
rem message is reached which of course depends on language of Windows.
for /F "usebackq skip=4 delims=" %%L in (`%SystemRoot%\System32\net.exe user`) do (
if "%%L"=="The command was successfully executed." goto :EOF
call :ProcessAccounts "%%L"
)
goto :EOF
rem Subrountine to process a line with user account names.
:ProcessAccounts
rem Get the line without the double quotes.
set "Line=%~1"
:NextUser
rem Get first 20 characters from line and next remove those 20 characters.
set "Name=%Line:~0,20%"
set "Line=%Line:~20%"
rem Remove all spaces at end of current user account name.
:TrimRight
if "%Name:~-1%"==" " (
set "Name=%Name:~0,-1%"
goto TrimRight
)
rem Check if this user account name is valid.
%SystemRoot%\System32\net.exe user "%Name%" 1>nul 2>nul
if not errorlevel 1 (
echo Valid user account name is: %Name%
rem Do here what should be done with this user account name.
)
rem Remove leading spaces from remaining line.
:TrimLeft
if "%Line:~0,1%"==" " (
set "Line=%Line:~1%"
goto TrimLeft
)
rem Is the shortened line now completely processed?
if not "%Line%"=="" goto NextUser
rem Exit the subroutine ProcessAccounts.
goto :EOF
也许有更好的解决方案来修剪左右空间,请参阅如何删除批处理文件中用户提供的输入的尾随和前导空格? https://stackoverflow.com/questions/3001999/
该批处理文件执行速度慢的原因是:
%SystemRoot%\System32\net.exe user "%Name%" 1>nul 2>nul
if not errorlevel 1 (
echo Valid user account name is: %Name%
rem Do here what should be done with this user account name.
)
通过将此块更改为
echo Valid user account name is: %Name%
rem Do here what should be done with this user account name.
使批处理文件变得非常非常快。
用户帐户名的验证net user "%Name%"
使批处理文件如此缓慢。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)