WMI 的 System Registry Provider 類別 StdRegProv 具有執行下列動作的方法:
建立或刪除登錄機碼。
建立或刪除具名值,這些具名值在索引鍵下時稱為條目。
使用新值的名稱和 SetBinaryValue、SetDWORDValue、SetExpandedStringValue、SetMultiStringValue或 SetStringValue 來建立具名值。 使用 DeleteValue 刪除具名值。
變更具名值。
使用值的名稱和 Set 方法(在先前的項目符號標示的項目中識別)來變更某個索引鍵下現有的具名值。 您必須知道值的名稱,才能加以變更。 如果您不知道索引鍵下的值名稱,請使用 EnumValues 方法來取得名稱。
本主題將討論下列各節:
- 使用 VBScript 建立登錄機碼
- 使用 PowerShell 和 VBScript 建立具名登錄值
使用 VBScript 建立登錄機碼
因為登錄是作業系統、應用程式和服務的中央組態資料庫,因此當您寫入登錄值或刪除鍵值時,請小心。
備註
您無法監視 HKEY_CURRENT_USER(HKCU)的 HKEY_CLASSES_ROOT 子機碼。 不建議監視 HKEY_USERS,因為子機碼會在載入 hives 時出現並消失。
下列程式代碼範例示範如何建立新的登錄機碼和子機碼。
HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set ObjRegistry = GetObject("winmgmts:{impersonationLevel = impersonate}!\\" & strComputer & "\root\default:StdRegProv")
strPath = "SOFTWARE\MyKey\MySubKey"
Return = objRegistry.CreateKey(HKEY_LOCAL_MACHINE, strPath)
If Return <> 0 Then
WScript.Echo "The operation failed." & Err.Number
WScript.Quit
Else
wScript.Echo "New registry key created" & VBCRLF & "HKLM\SOFTWARE\MYKey\"
End If
$HKEY_LOCAL_MACHINE = 2147483650
$strComputer = "."
$strPath = "SOFTWARE\MyKey\MySubKey"
$reg = [wmiclass]"\\$strComputer\root\default:StdRegprov"
[void]$reg.CreateKey($HKEY_LOCAL_MACHINE, $strPath)
使用 PowerShell 和 VBScript 建立具名登錄值
下列程式代碼範例示範如何在 HKEY_LOCAL_MACHINE\\SOFTWARE\MyKey\MySubKey 機碼下,建立名為 MultiStringValue 的具名值,這是在先前的腳本中建立的。 腳本會呼叫 StdRegProv.SetMultiStringValue,將字串值寫入新的具名值。
const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set objRegistry = _
GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\MyKey\MySubKey"
strValueName = "MultiStringValue"
arrStringValues = Array("one", "two","three", "four")
objRegistry.SetMultiStringValue HKEY_LOCAL_MACHINE, strKeyPath,_
strValueName, arrStringValues
' Read the values that were just written
objRegistry.GetMultiStringValue HKEY_LOCAL_MACHINE, strKeyPath,_
strValueName, arrStringValues
For Each strValue in arrStringValues
WScript.Echo strValue
Next
$HKEY_LOCAL_MACHINE = 2147483650
$strComputer = "."
$strPath = "SOFTWARE\MyKey\MySubKey"
$strValueName = "MultiStringValue"
$arrStringValues = @("one", "two","three", "four")
$reg = [wmiclass]"\\$strComputer\root\default:StdRegprov"
[void]$reg.SetMultiStringValue($HKEY_LOCAL_MACHINE, $strKeyPath, $strValueName, $arrStringValues)
$multiValues = $reg.GetMultiStringValue($HKEY_LOCAL_MACHINE, $strKeyPath, $strValueName)
$multiValues.sValue
使用 WMI 時,您無法在登入機碼上設定存取安全性。 不過,StdRegProv.CheckAccess 方法會將目前使用者的安全性設定與登錄機碼上的安全性描述元進行比較,以判斷使用者是否有特定許可權,例如 KEY_SET_VALUE。