Reputation: 14978
The method for getting a value in a registry key from PowerShell is:
Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion CommonFilesDir
However, that command returns some extra properties I don't usually want:
CommonFilesDir : C:\Program Files\Common Files
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows
PSChildName : CurrentVersion
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
I just want the actual value, a string in this case. To do that I have to use the more verbose:
$commonFilesDir = (Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion CommonFilesDir).CommonFilesDir
Other than writing my own alias, is there a way of not writing the property name twice and getting a string?
I could run the following command, but it returns a PSObject:
Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion | Select CommonFilesDir
Upvotes: 14
Views: 21581
Reputation: 3529
I'm going to replicate an answer by Mike Shepard here (see comment under Musaab's answer) since he has not posted it himself. It is better because you don't have to put the name of the variable in your code.
So you can take this:
Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion | Select -expandproperty CommonFilesDir
And instead do this:
$w = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion"
$q = "CommonFilesDir"
Get-ItemProperty $w | Select -expandproperty $q
Upvotes: 0
Reputation: 286
I'm new to PowerShell, but it seems to work in PowerShell 2 and 3 if you leave out the registry value name in Get-ItemProperty, using the value name only as a property:
(Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion).CommonFilesDir
or even shorter with the alias:
(gp HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion).CommonFilesDir
No repetition of the value name, clean, and it can't get much more succinct.
Upvotes: 14
Reputation: 3784
What about:
Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion | `
Select CommonFilesDir
Upvotes: 3
Reputation: 52480
This is no less clunky, but there's no repetition if that's an itch you need to scratch:
(gi HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion).GetValue("CommonFilesDir")
(personally I'd use $env:commonprogramfiles
but that's besides the point.)
Upvotes: 4