2014年7月11日 星期五

PowerShell Fist programming(1):如何使用cmdlets來新增和設定rigistry key

我們試著執行一個example,在HKEY_LOCAL_MACHINE\SOFTWARE底下建立一個新的"MyKey"registry key和將該registry keydefault value設定為"MyValue"
·         使用PowerShell console
使用New-Item cmdlet新增"MyKey" registry key和寫入"MyValue"default valuecommand如下:
New-Item -Path HKLM:\Software\MyKey -Value "MyValue"


新增的registry key和寫入該keydefault value,結果如下:







·         使用powrshell script
以下是PowerShell scriptsample
1、將寫好的script存成.ps1檔案。



2、在Powershell consol執行.ps1檔案



新增的registry key和寫入該keydefault value,結果如下:




Note

Predefined root keys
There are seven predefined root keys, traditionally named according to their constant handles defined in the Win32 API, or by synonymous abbreviations (depending on applications):
·         HKEY_LOCAL_MACHINE or HKLM
·         HKEY_CURRENT_CONFIG or HKCC (only in Windows 9x/Me and NT-based versions of Windows)
·         HKEY_CLASSES_ROOT or HKCR
·         HKEY_CURRENT_USER or HKCU
·         HKEY_USERS or HKU
·         HKEY_PERFORMANCE_DATA (only in NT-based versions of Windows, but invisible in the Windows Registry Editor)
·         HKEY_DYN_DATA (only in Windows 9x/Me, and visible in the Windows Registry Editor)

Note
以上的sample為使用New-Item cmdlet來新增registry key和寫入default value,該單一的指令可以細分為以下三的步驟:
Step1、使用 New-Item cmdlet建立一個registry key
Step 2、使用 Set-Item cmdlet assign一個default valueregistry key
以下為詳細說明:

Step1 Use PowerShell to Easily Create New Registry Keys

1Store the current working location by using the Push-Location cmdlet.



2Change the current working location to the appropriate registry drive( HKEY_LOCAL_MACHINE,HKLM) by using the Set-Location cmdlet.


3Use the Test-Path cmdlet to determine if the "SOFTWARE\MyKey" registry key already exists(傳回False).



4Use the New-Item cmdlet to create the new registry key.



5Use the Pop-Location cmdlet to return to the starting working location.



The newly created registry key is shown here in the Registry Editor tool.



Step2 Setting the default value for the key

在上一步驟還未設定 registry key default value,我們可以使用 Set-Item cmdletassign一個default valueregistry key
如以下的步驟:
  1. Supply the default value in the Value parameter of the Set-Item cmdlet.
The following command assigns the value "MyValue" to the default property value of the MyKey registry key that is contained in the HKCU:\Software location.
Set-Item -Path HKLM:\Software\MyKey -Value "MyValue"



The command does not return any information to the Windows PowerShell console when it runs. The modified registry key is shown here in the Registry Editor tool.



沒有留言:

張貼留言