我需要一种方法将当前用户的SID存储在一个变量中,我尝试了很多变种:
setlocal enableextensions
for /f "tokens=*" %%a in (
'"wmic path win32_useraccount where name='%UserName%' get sid"'
) do (
if not "%%a"==""
set myvar=%%a
echo/%%myvar%%=%myvar%
pause
endlocal
没有工作。
wmic path win32_useraccount where name='%UserName%' get sid
应该返回3行,我需要存储在变量中的第二行。
有人可以修复我的脚本吗?
编辑:我使用的是.cmd文件。
答案 0 :(得分:4)
这应该解决它:
for /f "delims= " %%a in ('"wmic path win32_useraccount where name='%UserName%' get sid"') do (
if not "%%a"=="SID" (
set myvar=%%a
goto :loop_end
)
)
:loop_end
echo %%myvar%%=%myvar%
注意FOR循环中的"delims= "
。它将在空格处分隔输入,这些输入包含在WMI查询输出的末尾。
条件if not "%%a"=="SID"
对于第二次迭代将为真,然后分配变量并退出循环。
希望有所帮助。
答案 1 :(得分:2)
我写这段代码对我有用
for /F "tokens=2" %%i in ('whoami /user /fo table /nh') do set usersid=%%i
答案 2 :(得分:1)
另一种解决方案可能是:
FOR /F "tokens=1,2 delims==" %%s IN ('wmic path win32_useraccount where name^='%username%' get sid /value ^| find /i "SID"') DO SET SID=%%t
答案 3 :(得分:0)
WMIC的另一个工作示例
@ECHO OFF
::SET Variables
SET _USERSID=NoValue
SET _User=QueryUserName
::Run the WMIC Command
@FOR /F "SKIP=1" %A IN ('"wmic useraccount where name='%_User%' get sid"') DO @FOR %B IN (%A) DO @SET _USERSID=%B
::Now do something with the SID IF EXISTS
:: Example below
cls
::Advise if the UserID was valid and echo out WMIC results
@IF %_USERSID% == NoValue ECHO USER ****%_User%**** NOT VALID
@ECHO WMIC Command %_USERSID%
::Example of using the WMIC %_USERSID% variable for something
@IF NOT %_USERSID% == NoValue REG DELETE "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%_USERSID%" /F
::SET ECHO Command Prompt ON
@ECHO ON
答案 4 :(得分:0)
希望这对你有用。
for /f "delims= " %%a in ('"wmic path win32_useraccount where name='%UserName%' get sid"') do (
if not "%%a"=="SID" (
set myvar=%%a
goto MESSAGE
)
)
goto MESSAGE
echo -----your message---------
for /f "delims= " %%a in ('"wmic path win32_useraccount where name='%UserName%' get sid"') do (
if not "%%a"=="SID" (
set myvar=%%a
goto MESSAGE
)
)
goto MESSAGE
:MESSAGE
echo.
echo Use this only if all other troubleshooting steps failed.
echo.
echo and restart the system
set /p yesno=[y/n]
if "%yesno%" equ "y" goto UNINSTALL
if "%yesno%" equ "Y" goto UNINSTALL
if "%yesno%" equ "yes" goto UNINSTALL
if "%yesno%" equ "Yes" goto UNINSTALL