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
One of the easiest ways to find registry keys and values is using the Get-ChildItem cmdlet. This uses PowerShell to get a registry value and more by enumerating items in PowerShell drives. In this case, that PowerShell drive is the HKLM drive found by running Get-PSDrive .
The Get-ItemProperty cmdlet gets the properties of the specified items. For example, you can use this cmdlet to get the value of the LastAccessTime property of a file object. You can also use this cmdlet to view registry entries and their values.
You can also use the New-ItemProperty cmdlet to create the registry entry and its value and then use Set-ItemProperty to change the value. For more information about the HKLM: drive, type Get-Help Get-PSDrive . For more information about how to use PowerShell to manage the registry, type Get-Help Registry .
Because registry keys are items on PowerShell drives, working with them is very similar to working with files and folders. One critical difference is that every item on a registry-based PowerShell drive is a container, just like a folder on a file system drive.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With