2

I call the powershell command in batch and want to save the $tmpVersion to batch variable "version".

set version = powershell.exe -Command "$tmpVersion = (Get-ItemProperty 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\myapp').DisplayVersion;"
4
  • Have you tried anything? Like, remove $tmpVersion = , or add $tmpVersion to the very end? Commented Apr 30, 2018 at 15:39
  • 1
    for /F "delims=" %%a in ('powershell.exe etc...') do set "version=%%a", but you need to also remove the $tmpVersion = part... Commented Apr 30, 2018 at 15:41
  • 1
    Don't use a batch file in the first place. Write the script in PowerShell. Commented Apr 30, 2018 at 16:08
  • Why not just use Reg.exe for this instead of a hybrid batch/script? Commented Apr 30, 2018 at 16:19

1 Answer 1

3

You can use a For loop to save the result of a command as a variable:

powershell.exe example:

@Echo Off
Set "RegRoot=HKLM"
Set "RegKey=SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\myapp"
Set "RegVal=DisplayVersion"
Set "Version="
For /F %%A In (
    'PowerShell -NoP -NoL "(GP '%RegRoot%:%RegKey%').%RegVal%" 2^>Nul'
) Do Set "Version=%%A"
If Not Defined Version Exit /B
Echo %Version%
Pause

reg.exe example:

@Echo Off
Set "RegRoot=HKLM"
Set "RegKey=SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\myapp"
Set "RegVal=DisplayVersion"
Set "Version="
For /F "Tokens=2*" %%A In ('Reg Query "%RegRoot%\%RegKey%" /V "%RegVal%" 2^>Nul'
) Do Set "Version=%%B"
If Not Defined Version Exit /B
Echo %Version%
Pause

WMIC.exe example:

@Echo Off
Set "RegRoot=&H80000002"
Set "RegKey=SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\myapp"
Set "RegVal=DisplayVersion"
Set "Version="
For /F Tokens^=2Delims^=^" %%A In ('WMIC Class StdRegProv
     Call GetStringValue hDefKey^="%RegRoot%" sSubKeyName^="%RegKey%"
      sValueName^="%RegVal%" 2^>Nul') Do Set "Version=%%A"
If Not Defined Version Exit /B
Echo %Version%
Pause
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.