Search code examples
powershellvariablesregistrymessagebox

Variable in messagebox returns string and not values


I'll put the request for installed (32bit) Java versions in one variable:

$java={Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*| Select-Object DisplayName, DisplayVersion| Where-Object {$_.DisplayName -like "Java ? Up*"}} 

When I ask

&$java 

it returns the wanted values. But when put this variable in a message box:

[System.Windows.Forms.MessageBox]::Show("Javaversion: $java","Softwareversion",0,[System.Windows.Forms.MessageBoxIcon]::Asterisk)

it returns the content of the variable ({Get-Item...) and not the Java versions.

What is format for the message box?


Solution

  • You define $java with a scriptblock (essentially a lambda expression/anonymous function). By using the call operator (&) you invoke/execute the scriptblock and in return get the result of the operation(s) defined in therein. However, by putting the variable into a string you insert the string representation of the scriptblock (essentially its definition) into the string.

    You should probably simply remove the curly braces, so that Get-ItemProperty is executed immediately and the results are assigned to the variable $java:

    $java = Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |
            Select-Object DisplayName, DisplayVersion |
            Where-Object {$_.DisplayName -like "Java ? Up*"}