store SID in a variable

2019-05-11 15:32发布

I need a way to store the current user's SID in a variable, I tried a lot of variants of:

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 

None are working.

wmic path win32_useraccount where name='%UserName%' get sid should be returning 3 lines, and I need the second one stored in a variable.

Can someone fix my script?

Edit: I am using a .cmd file.

4条回答
该账号已被封号
2楼-- · 2019-05-11 15:53

This should fix it:

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%

note the "delims= " in the FOR loop. It will separate the input at spaces, that are contained at the end of the output ouf your WMI query.

The condition if not "%%a"=="SID" will be true for the second iteration and then assign the variable and break out of the loop.

Hope that helps.

查看更多
看我几分像从前
3楼-- · 2019-05-11 16:02

Another solution could be:

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
查看更多
4楼-- · 2019-05-11 16:03

Another working example of 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
查看更多
孤傲高冷的网名
5楼-- · 2019-05-11 16:08

I write this code and it work good for me

for /F "tokens=2" %%i in ('whoami /user /fo table /nh') do set usersid=%%i
查看更多
登录 后发表回答