Pages

9/04/2011

Powershell: reset WSUS client for list of servers

##################################################################################
#
# WSUS Client Cleanup and Reinitialize
#
##################################################################################

$today = get-date

$list = get-content LIST.TXT

"=========================================================================="
" WSUS Client Cleanup and Reinitialize"
$today

foreach($server in $list) {
"--------------------------------------------------------------------------"
#net stop wuauserv
($svc = Get-WmiObject Win32_Service -ComputerName $server -Filter "name='wuauserv'") | out-null
if ($svc.started -eq $true) {
write $server "stopping wuauserv"
$result=$svc.StopService()
}
($svc = Get-WmiObject Win32_Service -ComputerName $server -Filter "name='wuauserv'") | out-null
if ($svc.started -eq $false) {
write $server "wuauserv stopped"
}

#Backup Registry
$result=([WmiClass]"\\$server\ROOT\CIMV2:Win32_Process").create("c:\windows\regedit /e c:\WSUS.REG HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate")
write $server "Backup Registry RESULT=" $result.returnvalue

#Cleanup Registry
write $server "Reg Clean"
$key = "SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate"
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $server)
$regKey = $reg.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate", $true)
if ($regKey.getvalue('AccountDomainSid')) {
$regKey.DeleteValue('AccountDomainSid')
"...removed AccountDomainSid"
}
if ($regKey.getvalue('PingID')) {
$regKey.DeleteValue('PingID')
"...removed PingID"
}
if ($regKey.getvalue('SusClientId')) {
$regKey.DeleteValue('SusClientId')
"...removed SusClientId"
}

$key2 = "SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update"
$regKey = $reg.OpenSubKey($key2, $true)
if ($regKey.getvalue('LastWaitTimeout')) {
$regKey.DeleteValue('LastWaitTimeout')
"...removed LastWaitTimeout"
}
if ($regKey.getvalue('DetectionStartTime')) {
$regKey.DeleteValue('DetectionStartTime')
"...removed DetectionStartTime"
}
if ($regKey.getvalue('NextDetectionTime')) {
$regKey.DeleteValue('NextDetectionTime')
"...removed NextDetectionTime"
}
if ($regKey.getvalue('AUState')) {
$regKey.DeleteValue('AUState')
"...removed AUState"
}
write $server "WSUS Reg Clean Completed"

#net start wuauserv
($svc = Get-WmiObject Win32_Service -ComputerName $server -Filter "name='wuauserv'") | out-null
if ($svc.StartMode -ne "Disabled") { $svc.StartService() | out-null } else {"wuauserv startup was disabled"}
($svc = Get-WmiObject Win32_Service -ComputerName $server -Filter "name='wuauserv'") | out-null
if ($svc.started) {
write $server "wuauserv started successfully"
}

#RESET WUAUCLT
$result=([WmiClass]"\\$server\ROOT\CIMV2:Win32_Process").create("wuauclt /resetauthorization /detectnow")
write $server "wuauclt reset RESULT=" $result.returnvalue

} #foreach
"=========================================================================="
##################################################################################

#is it necessary to clear WMI connections to free resources? If so how?
#if exist before attempting reg key remove

#RESULT CODES
# 0 {"$s Successful Completion."}
# 2 {"$s Access Denied."}
# 3 {"$s Insufficient Privilege."}
# 8 {"$s Unknown failure."}
# 9 {"$s Path Not Found."}
# 21 {"$s Invalid Parameter."}

Powershell: list servers that respond

##################################################################################
#
# Create list of all servers with machine accounts in AD that respond to PING
#
##################################################################################
# Create $list of AD machine accounts for Windows Servers
$ServerList = ".\SERVERLIST.TXT"
New-Item $ServerList -Type file -Force >$nul
"Gathering Server List..."
$strCategory = "computer"
$strOS = "Windows*Server*"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = ("OperatingSystem=$strOS")
$colProplist = "dnshostname"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
$colResults = $objSearcher.FindAll()
foreach ($objResult in $colResults) {
$objComputer = $objResult.Properties;
$Server = $objComputer.dnshostname
$Server = $Server -replace "\s{2,}", ""
$Server = $Server -replace "\.usa\.domain\.com", ""
if ($Server) {#skip null value
$Server
if (Test-Connection -ComputerName $Server -quiet -count 1) {#ping test
write-output $Server | out-file -encoding ASCII -filepath $ServerList -append
" .....OK"
}#if
}#if
}#foreach

Powershell: does reg key exist?

if (get-itemproperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate PingId -ErrorAction SilentlyContinue) { "True" } else { "False" }

Check services on all servers

##########################################################################################
#
# SVC-AUTO.PS1
# For all servers, find services with Automatic Startup that are not running
# Ignore SysMonLog("Performance Monitor Logs and Alerts")
#
##########################################################################################
#$startflag = $true
$startflag = $false
$inputfile = ".\dc-list.txt"
$names = Get-Content list.txt
$today = get-date
write "==========================================================================="
write " $today"
write " Automatic Service Status"
foreach($name in $names) {
write "---------------------------------------------------------------------------"
write-host " $name"
$svc = Get-WmiObject Win32_Service -ComputerName $name -erroraction SilentlyContinue
if ($svc) { #not null
foreach ($service in $svc) {
$svcname = $service.name
$svcdisplay = $service.displayname
$svcmode = $service.startMode
$svcstate = $service.state
if ($svcname -ne "SysMonLog") {
if ($svcmode -eq "Auto") {
if ($svcstate -eq "Stopped"){
write-host " $svcdisplay = DOWN"
if ($startflag) { #start it up
write-host " starting $svcdisplay"
$service.StartService() >$nul
sleep(10)
$svc = Get-WmiObject Win32_Service -ComputerName $name -Filter "name='$svcname'"
write-host " " $svcdisplay "..." $($svc.State)
} #if start flag
} #if stopped
}#if Auto
}#if
}#foreach service
}#if not null
else { write-host " ERROR: $name - No Response" }
}#foreach server
write "==========================================================================="

Cisco ios: piping output to include

Great, useful example:

sh int te1/3 | i clearing|drops|errors

QOS

WAN QOS

Groups.ps1

#powershell to create text files in a subdirectory with group members of a list of groups

$root=([ADSI]"").distinguishedName

$Groups=get-content groups.txt
$Folder=".\wsus-groups\"

foreach ($Group in $Groups) {
$out = $Folder+$Group+".TXT"
$outfile = $out -replace ' ','-'
#delete output file if it exists
if ( test-path $outfile ) { remove-item $outfile }

# "-----------------------------------"
# $Group+":"
$Group = [ADSI]("LDAP://CN=$Group,CN=Users,"+$root)
$list1 = $Group.member -Replace '\,.*$', ''
$list = $list1 -Replace 'CN=',''
# $list
$list | out-file -encoding ASCII $outfile -append
}

Checkuptime.ps1

#powershell to check uptime for list of servers after test for PING
$list = ".\wsus-groups\wsus-pri-group-1.txt"
$Servers = Get-Content $list
foreach($Server in $Servers) {
if (Test-Connection -ComputerName $Server -quiet -count 1) { #responds to PING
$wmi=Get-WmiObject -class Win32_OperatingSystem -computer $server
$LBTime=$wmi.ConvertToDateTime($wmi.Lastbootuptime)
[TimeSpan]$uptime=New-TimeSpan $LBTime $(get-date)
Write-host $server "Uptime: " $uptime.days "Days" $uptime.hours "Hours" $uptime.minutes "Minutes" $uptime.seconds "Seconds"
}
else {
Write-host $server "NO RESPONSE"
}
}#foreach

Enumerate Mailbox Permissions

$root = [ADSI]'LDAP://RootDSE' $dfDefaultRootPath = "LDAP://" + $root.DefaultNamingContext.tostring() $dfRoot = [ADSI]$dfDefaultRootPath $gfGALQueryFilter = "(&(&(&(mailnickname=*)(objectCategory=person)(objectClass=user))))" $dfsearcher = new-object System.DirectoryServices.DirectorySearcher($dfRoot) $dfsearcher.PageSize = 4500 $dfsearcher.Filter = $gfGALQueryFilter $dfsearcher.PropertiesToLoad.Add("msExchMailboxSecurityDescriptor") $srSearchResult = $dfsearcher.FindAll() "Mailbox ACE User" foreach ($emResult in $srSearchResult) { $uoUserobject = New-Object System.DirectoryServices.directoryentry $uoUserobject = $emResult.GetDirectoryEntry() $emProps = $emResult.Properties [byte[]]$DaclByte = $emProps["msexchmailboxsecuritydescriptor"][0] $adDACL = new-object System.DirectoryServices.ActiveDirectorySecurity $adDACL.SetSecurityDescriptorBinaryForm($DaclByte) $mbRightsacls =$adDACL.GetAccessRules($true, $false, [System.Security.Principal.SecurityIdentifier]) foreach ($ace in $mbRightsacls){ if($ace.IdentityReference.Value -ne "S-1-5-10" -band $ace.IdentityReference.Value -ne "S-1-5-18" -band $ace.IsInherited -ne $true){ $sidbind = "LDAP://" $AceName = $ace.IdentityReference.Value $aceuser = [ADSI]$sidbind if ($aceuser.name -ne $null){ $AceName = $aceuser.samaccountname } "" + $uoUserobject.DisplayName + " " + $AceName } } }

VMWare 5

Isolated browsing environment

Outlook performance and folder size

How item count in Outlook folders affects performance

UCS server hardware manual

How to configure the size limit for .pst and .ost files.

Outlook Encryption Options

VMware partition recovery

http://kb.vmware.com/kb/1002281
expert mode to make offset change stick

NFS changes in vSphere 5 and true scale-out NAS (Isilon) - Virtual Geek

Powershell Character Set Lookup

Awesome conversion of ansi code numbers to characters from the cmdline.
[int] [char] 'a'   returns:  97
[char] 97  returns:  a

Troubleshooting a problem led me to look at a registry key and it contained item named value that appeared to be numeric codes for characters separated by commas and a null character (0) so I pasted it in a text editor and used search and replace to remove ", 0".  Then I pasted that into the powershell cmdline to populated a string:

$LIST=97, 116, 108, 102, 115, 48, 49, 46, 117, 115, 97, 46, 100, 111, 109, 97, 105, 110, 46, 99, 111, 109

foreach ($char in $LIST) { [char] $char >>OUTPUT.TXT }

[char] 9786 !

More on aliased server names

regarding authentication during access to machines using a name other than its "real" name.
http://www.marc-antho-etc.net/blog/post/2010/09/08/Multiple-Names-for-a-File-and-Print-Server-Running-Windows-Server-2008-R2.aspx

Wildcard mask in ACLs

http://www.subnet-calculator.com/wildcard.php
Can be a real pain when I do in a hurry.  Secured a router so well I couldn't get into it....

START parameters