Monthly Archive

Categories

PowerShell and .NET

Registry 3

Lets look at changing registry values. In http://msmvps.com/blogs/richardsiddaway/archive/2010/07/16/registry-1.aspx  I showed how to read the registry. We’ll change the 4 values we found in that post

001
002
003
004
005
006
007
008
$reg = [Microsoft.Win32.Registry]::LocalMachine
$key = $reg.OpenSubKey("Software\ITKE PSAdmins", $true)
$key.SetValue("Dword Entry", 567 ,"Dword") 
$key.SetValue("String Entry", "My new string" ,"String") 
$key.SetValue("Expanded String Entry", "%COMPUTERNAME%" ,"ExpandString")

[string[]]$multi = "Z","Y","X"
$key.SetValue("Multi-string Entry", $multi ,"MultiString")

 

Open the key as we did before except this time add a second parameter. $true indicates that the key is opened in a readable state. The SetValue method can be used to set the appropriate values. The parameters are the name of the value, the new value and the data type. Notice that for the multi-string value we supply and array of strings.

The acceptable data types are:

PS> Get-Enum Microsoft.Win32.RegistryValueKind
Unknown
String
ExpandString
Binary
DWord
MultiString
QWord

Registry 2

In the previous post I showed this line

$reg = [Microsoft.Win32.Registry]::LocalMachine

 

which we used to determine which registry hive we would work with.

LocalMachine is a member of the Microsoft.Win32.RegistryHive enumeration.

An enumeration is a closed list.

I’ve added this function to my profile

001
002
003
004
005
006
function Get-Enum {
param (
    [string]$class
)   
    [enum]::GetNames("$class")
}

so that I can quickly find the members of an enumeration.

Use it like this

PS> Get-Enum Microsoft.Win32.RegistryHive
ClassesRoot
CurrentUser
LocalMachine
Users
PerformanceData
CurrentConfig
DynData

Registry 1

In this http://itknowledgeexchange.techtarget.com/powershell/wmi-and-the-registry/ and subsequent posts I looked at using WMI to work with the Registry.  As part of a series examining .NET classes that are useful to admins I thought it would be interesting to look at the Registry first.

We start by linking to a registry hive in this case HKLM – the local machine hive

$reg = [Microsoft.Win32.Registry]::LocalMachine

 

We can then access a subkey.

$key = $reg.OpenSubKey("Software\ITKE PSAdmins")

 

This is the example key I created in the WMI series so you need to read that to see how I created it.

We can get the number of values

$key.ValueCount
4

Their names

$key.GetValueNames()
String Entry
Expanded String Entry
Dword Entry
Multi-string Entry

 

and their types

$key.GetValueNames() | foreach {"$_   $($key.GetValueKind($_))"}

String Entry   String
Expanded String Entry   ExpandString
Dword Entry   DWord
Multi-string Entry   MultiString

 

and the actual values

$key.GetValueNames() | foreach {"$_   $($key.GetValue($_))"}
String Entry   This is a string
Expanded String Entry   C:\Users\Richard\AppData\Local\Temp
Dword Entry   101
Multi-string Entry   A B C D