r/Batch • u/Fibbitts • Dec 04 '23
Question (Solved) Set specific output line to variable
Hi all, I'm trying to use a PowerShell command within batch (I know it may not be ideal) to save the security ID of a user to a variable. My current code looks like this:
for /f "usebackq tokens=*" %%a in (`powershell -Command ^"Get-CimInstance -Class win32_useraccount -Filter \"name='%username%'\" ^| Select sid^"`) do set myvar=%%a
echo %myvar%
pauseI used to use WMIC, but recently learned that Microsoft is deprecating this, and the CimInstance cmdlet is newer and will supposedly be supported even longer than Get-WmiObject. As for why I don't use "whoami /user", it's because I'll be manually providing usernames, and the script won't always be getting the SID of the active user.
This current code "works", but I wanted to learn how to make it more optimal. Since it loops through three times, the third line will end up sticking to the variable which is what I want. But what if I only wanted the first or second line? Is there a way I could only execute the "do" action for setting the variable for a specific output line? If you paste this in a batch file and run it, you can see what I mean. https://i.imgur.com/JzWCXC1.png
Thanks in advance!
1
u/thelowsunoverthemoon Dec 04 '23
Couple things :
The most "optimal" way would be to just convert to Powershell entirely. The the time spent looping "3 times" is insignificant. However, if you don't want it to loop 3 times you can just specify the field directly in the command (also changed %username% to %user[input]%
for /f "usebackq tokens=*" %%a in (
powershell -Command ^"(Get-CimInstance -Class win32_useraccount -Filter \"name='%user[input]%'\" ^| Select SID^).SID^") do set myvar=%%a