Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMD Substring Extraction On Output Variable

Looking for guidance on performing substring extraction in a batch script on the variable of a command output. Specifically the command I am using is powershell (Get-CimInstance Win32_OperatingSystem).version

I have this variable set up successfully using for /f "tokens=*" %%i in ('"powershell (Get-CimInstance Win32_OperatingSystem).version"') do set OSvar=%%i

As you can see I am querying OS version, and I have an undisclosed, semi-valid use case for using this specific method to find it. Even if my reasoning behind using the above method to query may be misguided, I still want to learn how to perform substring extraction on this output, for my own edification. Finding a solution is less important than finding a solution in the given context.

Obviously, this will output something to the effect of "6.2.9200", "6.3.9600", or "10.0.XXXXXXX". I want to know how to extract the output before the 2nd decimal, but all of the attempts I've tried after researching are failing, including setting delims and using a second variable set equal to the first with :~0,3%. Can the gurus here help a guy out?

like image 841
Chocobits Avatar asked Nov 23 '25 10:11

Chocobits


1 Answers

Well, split the result by .

@echo off
for /f "tokens=1,2delims=." %%i in ('powershell (Get-CimInstance Win32_OperatingSystem^).version') do (
    set "OSvar=%%i.%%j"
)
echo %OSvar%

or a oneliner from the same code:

@echo off
for /f "tokens=1,2delims=." %%i in ('powershell (Get-CimInstance Win32_OperatingSystem^).version') do echo %%i.%%j

you can use the standard ver command as well;

@for /f "tokens=1-5,*delims=. " %%i in ('ver') do @set OSvar=%%l.%%m

Explanation as requested. Seeing as we split the string by . each token gets to assigned to a metavariable. In other words. Let's assume it is windows 10.0.18362.959 then tokens=1,2 will assign 10 to %%i and 0 to %%j


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!