Scripting Games 2010. Advanced Event 1 (Remote Registry)

Решил поучаствовать в Scripting Games 2010. Не знаю, насколько меня хватит, но начало положено.

Первое задание:
Event ScenarioThe boss has decided you need to check computers on the network. After the check has been completed, a registry key needs to be updated with the date and time of the check. You should test for the existence of the registry key, and if the registry key does not exist, it should be created. If the registry key does exist, it only needs to be updated. So far, this is the same scenario as the Beginner Event 1. Now for the Advanced criteria.

Design Criteria· Your script should be able to run remotely, which means you should be able to launch it on your local computer and target a remote computer.
· You should include the ability for the script to read a text file that includes a list of remote computer names.
· If you determine that your script will require administrative rights to run against a remote computer, you must include a test to ensure that the person launching the script has those rights. If the person running the computer does not have the appropriate rights, you should display a readable message informing the reader of that fact—and not simply display an error message.
· You should write your script in such a way that you can pass different registry keys to the script when it is called. In other words, do not hard-code the registry key path in your script. You can make it a default value if you wish, but do not require editing of the script to write to the registry in a different location.
· Your code should be written in such a way to promote code re-use. For example, consider writing the logic in either subroutines or functions.
· Style points will be granted to the script that includes command-line help and custom help messages.
· We are not concerned in this script with the code that performs the check, only the code that updates the registry key. The registry key should look like the one seen in the following image.

http://blogs.technet.com/heyscriptingguy/archive/2010/04/26/2010-scripting-games-advanced-event-1-updating-and-creating-registry-keys.aspx

Мое решение:

####################################################################################################################
# RemRegKeys.ps1 PowerShell shs 2010426
#
# Sripting games 2010 Advanced Event 1--Updating and Creating Registry Keys
#
# see http://blogs.technet.com/heyscriptingguy/archive/2010/04/26/2010-scripting-games-advanced-event-1-updating-and-creating-registry-keys.aspx
#
####################################################################################################################
#
param ($RegKeyName,$Path2CompList="C:\Scripts\PoSh.try\ScriptingGames\2010\1\Complist.txt")
#
## Function to test accessibility of the host (thnx 2 Xaegr ;))
function Test-Host ($Name)
{
    $ping = new-object System.Net.NetworkInformation.Ping
    trap {Write-Verbose "Ошибка пинга"; $False; continue}
    if ($ping.send($Name).Status -eq "Success" ) { $True }
    else { $False }
}
#====================================== Start of Script ==============================================================
cls
#
#if $RegKeyName param exist
if ($RegKeyName) {
	#Test the path to list of computers
	if (Test-Path $Path2CompList) {
		#for each computer in list...
		Get-Content $Path2CompList| foreach {
			#Save computer name in $CompName
			$CompName = $_
			#Test accessibility of the host
			Write-Host "Processing $CompName ..." -NoNewline
			if (Test-Host $CompName) {
				#...try to ...
				try {
					#...open remote registry base key
					$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $CompName)
					#...open remote registry subkey
					$RegKey = $reg.OpenSubKey($RegKeyName,$true)
					#if subkey exist...
					if ($RegKey) {
						Write-Host " Updating registry value..."
						#... update registry value
						$RegKey.SetValue("LastUpdate", $(Get-Date))
					}
					#if subkey does not exist...
					else {
						#Creating the registry key
						#(I don't create and update the value, becase "Design Criteria" doesn't require that if key doesn't exist)
						Write-Host " Creating subkey..."
						#create subkey
						$reg.CreateSubKey($RegKeyName)|Out-Null
					}
				}
				catch {
					Write-Host " Remote registry access denied!"
				}
			}
			#Host is not pingable
			else {
				Write-Host " Host is not pingable"
			}
		}
	}
	# Path to list of computers does not exist
	# Write error message
	else{
		Write-Host "`nFullPath to the list of computers ('$Path2CompList') does not exist"
	}
Write-Host ("`n`nAll done");
}
else{
	cls
	Write-Host ("Parameters required to run this script!`n`n`n"+
				"Help message:`n`n"+
				".\RemRegKey.ps1 <RegKeyName> [Path2CompList]`n`n"+
				"RegKeyName - Registry key to check or update`n"+
				"Path2Complist - full path to the file, that contains list of computers`n"+
				"`n`nExample:`n`t .\RemRegKey.ps1 sofware\SriptingGuys\2010SriptingGames`n`n"+
				"Sripting games 2010 Advanced Event 1--Updating and Creating Registry Keys`n"+
				"See http://blogs.technet.com/heyscriptingguy/archive/2010/04/26/2010-scripting-games-advanced-event-1-updating-and-creating-registry-keys.aspx")
}

Пример результа работы скрипта:

Processing ORG-20016-1 ... Updating registry value...
Processing ORG-20001-1 ... Host is not pingable
Processing ORG-200878-2 ... Remote registry access denied!
Processing ORG-200978-1 ... Remote registry access denied!
All done

4 Comments

  1. Кстати говоря, в задании было одно требование:
    1) you must include a test to ensure that the person launching the script has those rights

    в коде я не нашёл такой проверки. А делается она очень просто:

    function Test-Elevated {
    	$IsElevated = $false
    	foreach ($sid in [Security.Principal.WindowsIdentity]::GetCurrent().Groups) {
    		if ($sid.Translate([Security.Principal.SecurityIdentifier]).IsWellKnown( `
    			[Security.Principal.WellKnownSidType]::BuiltinAdministratorsSid)) {
    			$IsElevated=$true
    		}
    	}
    	$IsElevated
    }
    • Полная цитата звучит так: “If you determine that your script will require administrative rights to run against a remote computer, you must include a test to ensure that the person launching the script has those rights. If the person running the computer does not have the appropriate rights, you should display a readable message informing the reader of that fact—and not simply display an error message. ”

      “Если вы определите, что скрипт требует наличия административных прав для выполнения действий над удаленным компьютером, вы должны предусмотреть проверку того, что пользователь запустивший этот скрипт, обладает соответствующими правами. Если пользователь, запустивший этот скрипт не обладает соотвествующими правами, вы должны отобразить сообщение, информирующее пользователя об этом факте и не выводить сообщение об ошибке.”

      “Your script should be able to run remotely, which means you should be able to launch it on your local computer and target a remote computer.”
      “Ваш скрипт должен уметь работать с удаленными компьютерами. Это означает, что его можно будет запустить на вашем локальном компьютере и указать, что действия он должен выполнять на удаленном компьютере”

      Ни о каком повышении привелегий речь не идет. Речь идет о том, что если прав недостаточно для выполнения действий на удаленном компьютере, то необходимо уведомить об этом пользовтеля. Мой скрипт делает это при помощи блока try{…} catch{…}

      Upd.

Leave a Reply

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.