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.
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.
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
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
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