はじめに
Powershellでよくレジストリの追加や削除、変更操作を実施することがあるので、簡単に利用でいるようにクラス化してみました。
基本、このクラスを読み込んで好きな操作のメソッドを呼び出せすだけでOKです。
レジストリ操作クラス
registry.ps1
class Registry {
    # Constructor
    Registry(){}
    # Check registry entry value
    # $path  registry path
    # $name  registry entry name
    [bool] IsExistRegistryEntry($path, $name) {
        try {
            $item = Get-Item -Path "Registry::$path" -ErrorAction Strop
            if($item -ne $null) {
                $value = $item.GetValue($name)
                if($value -ne $null){
                    return $true
                } else {
                    return $false
                }
            } else {
                return $false
            }
        } catch {
            return $false
        }
    }
    # Get resitry entry value
    # $path   registry path
    # $name   registry entry name
    # $defval return value when not exist registry entry
    [string] GetRegistryEntry($path, $name, $defval) {
        try {
            $item = Get-Item -Path "Registry::$path" -ErrorAction Stop
            if ($item -ne $null) {
                $value = $item.GetValue($name)
                if ($value -eq $null) {
                    return $defval
                } else {
                    return $value
                }
            } else {
                return $defval
            }
        } catch {
            return $defval
        }
    }
    # Set registory entry value
    # $path  registry path
    # $name  registry entry name to set
    # $vaule registry entry value to set
    [void] SetRegistoryEntry($path, $name, $value) {
        if ((Test-Path $path) -eq $false) {
            New-Item -Force $path | Out-Null
        }
        Set-ItemProperty $path -name $name -value $value
    }
    # Delete registry entry
    # $path  registry path
    # $name  registry entry name to delete
    [void] DelRegistryEntry($path, $name) {
        if (Test-Path $path) {
            $key = Get-Item $path
            if ($key.GetValue($name, $null) -ne $null) {
                Remove-ItemProperty $path -name $name
            }
        }
    }
    # Delete registry key
    # $path  registry path to delete
    [void] DelRegistryKey($path) {
        if (Test-Path $path) {
            Remove-Item $path
        }
    }
}
使い方
上記で作成したクラスの使い方は下記を参考にしてください。
sample.ps1
# include
."Sample\registry.ps1"
$reg = [Registry]::new()
$reg.IsExistRegistryEntry("HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate", "WUServer")
$reg.GetRegistoryEntry("HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate", "WUServer", $null)
$reg.SetRegistoryEntry("HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate", "WUServer", "http://xxxxxx.xxx.xxx:8530")
$reg.DelRegistoryEntry("HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate", "WUServer")
$reg.DelRegistryKey("HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate")
さいごに
powershellで効率化などを考えている方など、コードを書く際は、よく使う処理をclass化したほうが、すっきりした見た目にもなります。
ぜひ、参考にしてみてください。

 
  
  
  
  
