Store SID in a variable

I need a way to store the current SID of the user in a variable, I tried many options:

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 

Does not work.

wmic path win32_useraccount where name='%UserName%' get sid should return 3 rows, and I need a second one, which is stored in a variable.

Can someone fix my script?

Edit: I am using a .cmd file.

+3
source share
4 answers

This should fix:

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%

Pay attention to "delims= "the FOR loop. It will separate the input in spaces that are at the end of the output of your WMI request.

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

Hope this helps.

+4
source

,

for /F "tokens=2" %%i in ('whoami /user /fo table /nh') do set usersid=%%i
+2

Another solution might 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
+1
source

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
0
source

Source: https://habr.com/ru/post/1748983/


All Articles