PowerShell Tips – Basic Script Template for Server Administration

After a few years of hacking other people scripts I found on Google, I came up with a basic template that I would apply everytime when I adapt a script.  There are two purposes:

  1.  ensure the input parameters are consistent amoung my scripts
  2.  ensure the output format are consistent amoung my scripts.

The sample I am using for the demostration in this post, is one of my scripts to check a registry key on one or many servers.


param
(
[Parameter(Position=0,ValuefromPipeline=$true)][string][alias("cn")]$computer,
[Parameter(Position=1,ValuefromPipeline=$false)][string]$computerlist
)

If (-not ($computer -or $computerlist))
{
$computers = $Env:COMPUTERNAME
}

If ($computer)
{
$computers = $computer
}

If ($computerlist)
{
$computers = Get-Content $computerlist
}
foreach ($system in $computers) {
$key64="software\Wow6432Node\Huntsman\patching"
$key="software\MyCompany\patching"
$keyvalue="Patch_Category"

$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$system)
$RegSubKey = $Reg.OpenSubKey($key64)
Try
{
$RegSubKey = $Reg.OpenSubKey($key64)
$value = $RegSubKey.GetValue($keyvalue)
}
catch
{
$RegSubKey = $Reg.OpenSubKey($key)
$value = $RegSubKey.GetValue($keyvalue)

}
$output = new-object PSObject
$output | add-member NoteProperty "ComputerName" -value $system
$output | add-member NoteProperty $keyvalue -value $value

$output

}

This script will take one of the two input as parameter, a computer name as string (if not default to localhost), or computers, which expect a list in text file.  If will then process the input and feed the results to a For loop.  The content of the For loop can be updated to adapt any scripts I find in Google for any purpoes.  For each of the expect output, I feed it as a PSObject, which should output nicely to a sort of table format by itself.

This script can then feed into my next script, which will allow multithreading to speed up the process.

Leave a Reply

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