Pages

11/30/2011

Isilon + VMWare

Recommendations for high i/o performance:   - move to iscsi mounted datastore
And/or
  - set folders for these vms to 2x protection level
  - Set smartcache to disabled
  - Set data access pattern to random

Run FlexProtect & MultiScan:
          Cluster > Operations > Summary > Start Job

Isilon

Isilon OneFS 6.5.4.4, lsassd has a memory leak.  Upgraded to 6.5.4.9 fixed memory leak and also supposed to emulate support for extended attributes.
Interesting:  running top from SSH console of machine showed lsassd process grow over a period of a few hours.  Isilon has another process that checks for any processes taking up over 512MB memory and kills them.
In this case, that disconnected all my SecureCopy sessions.

11/18/2011

Cisco: My router doesn't show the time in the log

Stupid router log says like "23w1d" instead of the date.  What do I do?

service timestamps log datetime

10/03/2011

Automated Remote Install of SCOM client

###############################################################################################################
#  SCOM-INST.PS1
# Install SCOM Agent on a list of machines.

$rootMS = "RMS01"
$list = "c:\server-list.txt"
clear-host
$Servers = Get-Content $list

#attach SCOM SnapIn
    Add-PSSnapin "Microsoft.EnterpriseManagement.OperationsManager.Client" -ErrorVariable errSnapin;
    Set-Location "OperationsManagerMonitoring::" -ErrorVariable errSnapin;
    new-managementGroupConnection -ConnectionString:$rootMS -ErrorVariable errSnapin;
    set-location $rootMS -ErrorVariable errSnapin;
#
#install SCOM client
    $DiscoverCnfg = New-WindowsDiscoveryConfiguration -computername:$servers -performverification:$true

-computertype:"server"
    $ms = Get-rootManagementServer
    $DiscoverResults = Start-Discovery -managementserver $ms -windowsdiscoveryconfiguration:$DiscoverCnfg

$DiscoverResults.CustomMonitoringObjects
    if ($DiscoverResults.CustomMonitoringObjects) {
        install-agent -ManagementServer $ms -AgentManagedComputer: $DiscoverResults.custommonitoringobjects
        }
    else {
        write-host "ERROR:  Machine(s) not found"
        }


#
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

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

7/25/2011

Security: Finding printers with Google

Why would someone put their printer on the internet????  I really don't know, but they are out there.


Finding Printers with Google


Sometimes for convenience admins will put links to there printers' web interfaces on an Intranet site so they can easily admin them or pull off stored documents. Well, sometimes an Intranet is not really just an Intranet but accessible via the Internet. Google is a great way to find these printers. Here are a few search strings that may be of interest:

Ricoh Savins (Since these printer frequently store documents where to can be downloaded this can be a real killer for security)
          intitle:"web image monitor"
          "/web/user/en/websys/webArch/mainFrame.cgi"
          inurl:"/en/sts_index.cgi"

HP Jetdirects (Varies greatly from model to model)
          inurl:hp/device/this.LCDispatcher

6/24/2011

check server time zones

##########################################################################################
# CHECK-TZONE.PS1
#
# Report local time and time zone for list of servers
#
##########################################################################################

$colResults = get-content C:\UTIL\WSUS-GROUPS\WSUS-USA-REMOTE.TXT
$time_zones = @()
clear-host
 "SERVER TIME ZONES"  
 ""
 "SERVER          `tTIME    `t TIME ZONE"
 "----------------`t--------`t --------------------------------------"
 
foreach ($result in $colResults) {
  $hour = ""
  $min = ""
  $sec = ""
  $comp = ""
  $t = ""
   $computer = $result 
  $comp = "{0,-16}" -f $computer
  $timezone = Get-WMIObject -class Win32_TimeZone -ComputerName $computer -erroraction SilentlyContinue
  $dt = gwmi win32_localtime -computer $computer -erroraction SilentlyContinue
  [string] $hour = [System.Convert]::ToString($dt.Hour)
  $hour = $hour.padleft(2,"0")
  [string] $min = [System.Convert]::ToString($dt.Minute)
  $min = $min.padleft(2,"0")
  [string] $sec = [System.Convert]::ToString($dt.Second)
  $sec = $sec.padleft(2,"0")
  $t = $hour + ":" + $min + ":" + $sec
  if ($dt) { write-host "$comp`t$t`t" $timezone.Description }
}

6/22/2011

This script installs the Operations Management Server PowerShell SnapIn onto a given computer

Install SCOM SnapIn: "This script installs the Operations Management Server PowerShell SnapIn onto a given computer"
#=============================================================================#
#                                                                             #
# Install-SCOMSnapIn.ps1                                                      #
# Powershell Script to install Operations Management Server SnapIn            #
# Author: Jeremy Engel                                                        #
# Date: 04.13.2011                                                            #
# Version: 1.1.0                                                              #
#                                                                             #
#=============================================================================#

Param([Parameter(Mandatory = $true)]$Computer,
      [Parameter(Mandatory = $true)]$ManagementServer
      )

$fileRepository = "\\$ManagementServer\c$\Program Files\System Center Operations Manager 2007"
$rootPath = "C:\Program Files\System Center Operations Manager 2007\SnapIn"

$files = @("Microsoft.EnterpriseManagement.OperationsManager.ClientShell.dll",
           "Microsoft.EnterpriseManagement.OperationsManager.ClientShell.dll-help.xml",
           "Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Format.ps1xml",
           "Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Types.ps1xml"
           )
$sdkfiles = @("Microsoft.EnterpriseManagement.OperationsManager.Common.dll",
              "Microsoft.EnterpriseManagement.OperationsManager.dll"
              )

function Main {
  $remotePath = $rootPath.Replace("C:","\\$Computer\c$")
  if(!(Test-Path $remotePath)) { $null = New-Item $remotePath -Type Directory }
  foreach($file in $files) { 
    if(!(Test-Path "$remotePath\$file")) { 
      Copy-Item -Path "$fileRepository\$file" -Destination $remotePath
      }
    }
  foreach($file in $sdkfiles) {
    if(!(Test-Path "$remotePath\$file")) {
      Copy-Item -Path "$fileRepository\SDK Binaries\$file" -Destination $remotePath
      }
    }
  $hklm = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$Computer)
  $scom = $hklm.CreateSubKey("SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns\Microsoft.EnterpriseManagement.OperationsManager.Client")
  $scom.SetValue("ApplicationBase",$rootPath,"String")
  $scom.SetValue("AssemblyName","Microsoft.EnterpriseManagement.OperationsManager.ClientShell, Version=6.0.4900.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","String")
  $scom.SetValue("ModuleName","$rootPath\Microsoft.EnterpriseManagement.OperationsManager.ClientShell.dll","String")
  $scom.SetValue("PowerShellVersion","1.0","String")
  $scom.SetValue("Vendor","Microsoft Corporation","String")
  $scom.SetValue("Version","6.0.4900.0","String")
  $scom.SetValue("Description","Microsoft Operations Manager Shell Snapin","String")
  $scom.SetValue("Types","$rootPath\Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Types.ps1xml","String")
  $scom.SetValue("Formats","$rootPath\Microsoft.EnterpriseManagement.OperationsManager.ClientShell.Format.ps1xml","String")
  }

Main

6/21/2011

Tweaking Windows 7 / Vista TCP/IP settings

SpeedGuide.net :: Windows 7, Vista, 2008 Tweaks: "Tweaking Windows 7 / Vista TCP/IP settings"
Disable Windows Scaling heuristics

Windows Vista/7 has the ability to automatically change its own TCP Window auto-tuning behavior to a more conservative state regardless of any user settings. It is possible for Windows to override the autotuninlevel even after an user sets their custom TCP auto-tuning level. When that behavior occurs, the "netsh int tcp show global" command displays the following message:


** The above autotuninglevel setting is the result of Windows Scaling heuristics
overriding any local/policy configuration on at least one profile.

To prevent that behavior and enforce any user-set TCP Window auto-tunning level, you should execute the following command:


netsh int tcp set heuristics disabled

possible settings are: disabled,enabled,default (sets to the Windows default state)
recommended: disabled (to retain user-set auto-tuning level)

Note this should be executed in elevated command prompt (with admin priviledges) before setting the autotuninlevel in next section. If the command is accepted by the OS you will see an "Ok." on a new line.

The corresponding Registry value (not necessary to edit if setting via netsh) is located in:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters
EnableWsd=0   (default: 1, recommended: 0)


TCP Auto-Tuning

To turn off the default RWIN auto tuning behavior, (in elevated command prompt) type:

netsh int tcp set global autotuninglevel=disabled

The default auto-tuning level is "normal", and the possible settings for the above command are:

disabled: uses a fixed value for the tcp receive window. Limits it to 64KB (limited at 65535).
highlyrestricted: allows the receive window to grow beyond its default value, very conservatively
restricted: somewhat restricted growth of the tcp receive window beyond its default value
normal: default value, allows the receive window to grow to accommodate most conditions
experimental: allows the receive window to grow to accommodate extreme scenarios (not recommended, it can degrade performance in common scenarios, only intended for research purposes. It enables RWIN values of over 16 MB)

Our recommendation: normal (unless you're experiencing problems).

If you're experiencing problems with your NAT router or SPI firewall, try the "restricted", "highlyrestricted", or even "disabled" state.

Notes:
- Reportedly, some older residential NAT routers with a SPI firewall may have problems with enabled tcp auto-tuning in it's "normal" state, resulting in slow speeds, packet loss, reduced network performance in general.
- auto-tuning also causes problems with really old routers that do not support TCP Windows scaling. See MSKB 935400
- netsh set commands take effect immediately after executing, there is no need to reboot.
- sometimes when using "normal" mode and long lasting connections (p2p software / torrents), tcp windows can get very large and consume too much resources, if you're experiencing problems try a more conservative (restricted) setting.

Disable TCP autotuning

How to disable the TCP autotuning diagnostic tool: "How to disable the TCP autotuning diagnostic tool"

6/17/2011

Put list of servers in SCOM maintenance mode

- have a folder which contains text files with lists of servers to define groups.
$rootMS = "PRIRMS01"
$Folder="c:\util\wsus-groups\"

"SET MAINTENANCE MODE"
"LISTS:"
$list = get-childitem $Folder -Name 
$list = $list -replace ".TXT",""
$list | format-wide {$_} -Column 3 -Force

$group = Read-Host "LIST [WSUS-Test-Group-2]"
if (!$group) { $group = "WSUS-Test-Group-2" }
$t = Read-Host " TIME[60]"
if (!$t) { $t = "60" }
$comment = Read-Host "COMMENT [Windows Updates]"
if (!$comment) { $comment = "Windows Updates" }

#####################################
#attach SCOM SnapIn
Add-PSSnapin "Microsoft.EnterpriseManagement.OperationsManager.Client" -ErrorVariable errSnapin; 
Set-Location "OperationsManagerMonitoring::" -ErrorVariable errSnapin; 
new-managementGroupConnection -ConnectionString:$rootMS -ErrorVariable errSnapin; 
set-location $rootMS -ErrorVariable errSnapin;
#

$File = $Folder + $group + ".TXT"
$servers = get-content $File
"Setting maintenance mode for $t minutes:"
foreach ($server in $servers) {
write-host "    $server" -nonewline
    $strServer = Get-Agent | Where-object {$_.Name -match $server}
    if (!$strServer) { write-host " - ERROR finding SCOM Agent!" -nonewline }
    if ($strServer) { $strServer.HostComputer | New-MaintenanceWindow -StartTime (Get-Date) -EndTime (Get-Date).AddMinutes($t)-Comment $comment }
 write-host ""
    }

"COMPLETE"
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

6/09/2011

POWERSHELL List Updates in WSUS

[void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration")
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer('WSUS02',$False,80)
#Get all updates
$updates = $wsus.GetUpdates()
#Iterate every update and output some basic info about it
$collection = @()
ForEach ($update in $updates) {
#$update
$product = $update.ProductTitles
$product.type
 $obj = New-Object System.Object
 $obj | Add-Member -type NoteProperty -name Date -value $update.CreationDate.ToString()
 $obj | Add-Member -type NoteProperty -name Approved -value $update.IsApproved.ToString()
 $obj | Add-Member -type NoteProperty -name Class -value $update.UpdateClassificationTitle
 $obj | Add-Member -type NoteProperty -name Product -value $product
 $obj | Add-Member -type NoteProperty -name Title -value $update.Title
 $collection += $obj 
}#ForEach

$collection | Sort-Object Date | export-csv .\updates.csv -force

UCS on Brian Hedlund blog

Cisco UCS Networking videos (in HD), Updated & Improved!: "Cisco UCS Networking videos (in HD), Updated & Improved!"

Publish your own update in WSUS!

Local Update Publisher | Download Local Update Publisher software for free at SourceForge.net: "Local Update Publisher allows system administrators to publish their own updates to Windows Server Update Services using WSUS local publishing."

5/31/2011

List Exchange 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
  }
 }
}

5/25/2011

Last Logon

Fixed this to output into something I can open in Excel.
# PSLastLogon.ps1
# PowerShell script to determine when each user in the domain last
# logged on.
#

#delete output file if it exists
if ( test-path lastlogon.csv ) { remove-item lastlogon.csv }

Trap {"Error: $_"; Break;}
 
$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 4000
$Searcher.SearchScope = "subtree"
 
$Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
$Searcher.PropertiesToLoad.Add("distinguishedName") > $Null
$Searcher.PropertiesToLoad.Add("lastLogon") > $Null
 
# Create hash table of users and their last logon dates.
$arrUsers = @{}
 
# Enumerate all Domain Controllers.
ForEach ($DC In $D.DomainControllers)
{
    $Server = $DC.Name
    $Test = $Server -replace "\..*$",""
    $Test = $Test.ToUpper()
 #   $Test
  if (!($Test.startswith("SECDC02"))) {
    $Searcher.SearchRoot = "LDAP://$Server/" + $Domain.distinguishedName
    $Results = $Searcher.FindAll()
    ForEach ($Result In $Results)
    {
        $DN = $Result.Properties.Item("distinguishedName")
        $LL = $Result.Properties.Item("lastLogon")
        If ($LL.Count -eq 0)
        {
           $Last = [DateTime]0
        }
        Else
        {
            $Last = [DateTime]$LL.Item(0)
        }
        If ($Last -eq 0)
        {
            $LastLogon = $Last.AddYears(1600)
        }
        Else
        {
            $LastLogon = $Last.AddYears(1600).ToLocalTime()
        }
        If ($arrUsers.ContainsKey("$DN"))
        {
            If ($LastLogon -gt $arrUsers["$DN"])
            {
                $arrUsers["$DN"] = $LastLogon
            }
        }
       Else
        {
            $arrUsers.Add("$DN", $LastLogon)
        }
    }#foreach
  }#if
}#foreach
 
# Output latest last logon date for each user.
$Users = $arrUsers.Keys
ForEach ($DN In $Users)
{
    $Date = $arrUsers["$DN"]
    $output = '"'+$DN+'",'+$Date
    $output | out-file -encoding ASCII  lastlogon.csv -append
}

CaliTechnical: Make ur Internet n Bandwidth Rapid - Rapid Speeds

CaliTechnical: Make ur Internet n Bandwidth Rapid - Rapid Speeds: "TCP/IP tweaks, patches & Manual registry hacks for Windows Vista/2008"
TCP Auto-Tuning

To turn off the default RWIN auto tuning behavior, (in elevated command prompt) type:

netsh int tcp set global autotuninglevel=disabled

The default auto-tuning level is "normal", and the possible settings for the above command are:

disabled: uses a fixed value for the tcp receive window. Limits it to 64KB (limited at 65535).
higlyrestricted: allows the receive window to grow beyond its default value, very conservatively
restricted: somewhat restricted growth of the tcp receive window beyond its default value
normal: default value, allows the receive window to grow to accommodate most conditions
experimental: allows the receive window to grow to accommodate extreme scenarios (not recommended, it can degrade performance in common scenarios, only intended for research purposes. It enables RWIN values of over 16 MB)

Our recommendation: normal (unless you're experiencing problems).

If you're experiencing problems with your NAT router or SPI firewall, try the "restricted", "highlyrestricted", or even "disabled" state.

Notes:
- Reportedly, many home NAT routers with a SPI firewall may have problems with enabled tcp auto-tuning in it's "normal" state, resulting in slow speeds, packet loss, and general reduced network performance.
- auto-tuning also causes problems with older routers that do not support TCP Windows scaling.
- netsh set commands take effect immediately after executing, there is no need to reboot.
- sometimes when using "normal" mode and long lasting connections (p2p software / torrents), tcp windows can get very large and consume too much resources, if you're experiencing problems try a more conservative setting.

If you're experiencing problems with Auto-Tuning, see also:
MS KB 835400 - email issues
MS KB 934430 - network connectivity behind firewall problems
MS KB 940646 - 3G WWAN throughput issues
MS KB 929868 - web browsing issues
MS KB 932170 - slow network file transfer

The above are the M$ Knowledge based articles. To view them input the following in your browser




Code:



http://support.microsoft.com/kb/



Example to view MS KB 83540 type in:


Code:



http://support.microsoft.com/kb/935400



Compound TCP - Improve throughput

The traditional slow-start and congestion avoidance algorithms in TCP help avoid network congestion by gradually increasing the TCP window at the beginning of transfers until the TCP Receive Window boundary is reached, or packet loss occurs. For broadband internet connections that combine high TCP Window with higher latency (high BDP), these algorithms do not increase the TCP windows fast enough to fully utilize the bandwidth of the connection.

Compound TCP (CTCP) is a newer method, available in Vista and Server 2008 (there is also a hotfix available for XP/2003). CTCP increases the TCP send window more aggressively for broadband connections (with large RWIN and BDP). CTCP attempts to maximize throughput by monitoring delay variations and packet loss. It also ensures that its behavior does not impact other TCP connections negatively.

By default, Vista has CTCP turned off, and Server 2008 turned on. Turning this option on can significantly increase throughput.

To enable CTCP, in elevated command prompt type:

netsh int tcp set global congestionprovider=ctcp

To disable CTCP:

netsh int tcp set global congestionprovider=none

Possible options are: ctcp, none, default (restores the system default value).
Recommended setting: ctcp

It is better to use this newer generation CTCP congestion control algorithm for most broadband connections, I recommend it being turned on.

ECN Capability

ECN (Explicit Congestion Notification) is a mechanism that provides routers with an alternate method of communicating network congestion. It is aimed to decrease retransmissions. In essence, ECN assumes that the cause of any packet loss is router congestion. It allows routers experiencing congestion to mark packets and allow clients to automatically lower their transfer rate to prevent further packet loss. ECN is disabled by default in Vista, as it is possible that it may cause problems with some older routers that do not support this feature.

To check whether your router supports ECN, you can use the Microsoft Internet Connectivity Evaluation Tool



Code:



http://www.microsoft.com/windows/using/tools/igd/default.mspx



. The results will be displayed under "Traffic Congestion Test".

To enable ECN, in elevated command prompt type:

netsh int tcp set global ecncapability=enabled

Possible settings are: enabled, disabled, default (restores the state to the system default).
The default state is: disabled
Our recommendation: disabled

RSS - Receive-side Scaling

The receive-side scaling setting enables parallelized processing of received packets on multiple processors, while avoiding packet reordering. It avoids packet reordering y separating packets into "flows", and using a single processor for processing all the packets for a given flow. Packets are separated into flows by computing a hash value based on specific fields in each packet, and the resulting hash values are used to select a processor for processing the flow. This approach ensures that all packets belonging to a given TCP connection will be queued to the same processor, in the same order that they were received by the network adapter.

To set RSS:

netsh int tcp set global rss=enabled

Possible rss settings are: disabled, enabled, default (restores rss state to the system default).
Default state is: enabled
Recommended: enabled (if you have 2 or more processor cores and a NIC that can handle RSS)

Manually tuning Registry Parameters

Many of the registry keys tuning TCP/IP parameters from previous Windows versions no longer work in Vista and Server 2008. Below is a list of the few we've confirmed to still work. Note that for changes to these settings to take effect the computer needs to be rebooted. As always, a registry backup is recommended if making any changes, and some proficiency in using regedit is required.

In regedit (Start icon > Run > type: regedit while logged in as administrator), you can navigate and edit the following keys.

MTU (Maximum Transmission Unit) - the maximum packet size.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{...}\
MTU=1500 (DWORD, entry does not exist by default)

The {....} part of the above path is the unique identifier of your network adapter. You can recognize the correct adapter by looking at it's IP address, if obtaining IP automatically labeled by: DhcpIPAddress=192.168.x.x text value, for example.

We recommend leaving this at default, unless you want to lower it. Vista uses the largest possible packet size for the underlying network by default.

Note: In some test environments, the correct MTU entry may be offset by 8. The 8 offset seems to coincide with the size of the PPPoE overhead. Check the result with the TCP Analyzer.



TCP 1323 Options

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\
Tcp1323Opts=1 (DWORD, entry created automatically by Windows when you run the "netsh int tcp set global autotuninglvl=..." command, set to 0 by default).

Setting this seems to have no effect, since auto-tuning uses the TCP 1323 scale factor and changes it on the fly, disregarding this setting. Additional testing may be required to determine it's effect if auto-tuning is turned off. Setting it to 1 is best for broadband connections.



NetDMA

NetDMA enables support for advanced direct memory access. In essence, it provides the ability to more efficiently move network data by minimizing CPU usage. NetDMA frees the CPU from handling memory data transfers between network card data buffers and application buffers by using a DMA engine.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
EnableTCPA=1 (DWORD, 1 to enable, 0 to disable NetDMA. Value not present by default in Vista)

Recommended setting is 1, a new DWORD value may need to be created if not already present in the registry.



DefaultTTL

TTL can be safely left alone in many cases. It is a limit to the time and number of hops/routers a packet will travel before being discarded. A number that's too small risks packets being discarded before reaching their destination. A number that's too large (over 128) will cause delay in when lost IP packets are discarded.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
DefaultTTL=64 (DWORD, set to a decimal value between 32 and 128. Recommended: 64)



TcpMaxDataRetransmissions

Determines how many times unacknowledged data (non-connect segment) is retransmitted before TCP aborts the connection. The retransmission timeout is doubled with each successive retransmission on a connection. It is reset when responses resume.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
TCPMaxDataRetransmissions=7 (DWORD, recommended: between 3 and 10, default registry value 255, default 5 in documentation)



SynAttackProtect

This undocumented setting provides protection against SYN denial of service (DoS) attacks. When enabled, connections timeout sooner if SYN attack is detected. When set at 1, TCPMaxDataRetransmissions can be lowered further.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
SynAttackProtect=1 (DWORD, recommended: 1, not present in registry by default)

TcpTimedWaitDelay (port allocation)

Short lived (ephemeral) TCP/IP ports above 1024 are allocated as needed by the OS. The default Vista values have improved from previous Windows versions, and are usually sufficient under normal load. However, in some instances under heavy load it it may be necessary to adjust the settings below to tweak the availability of user ports requested by an application.

If the default limits are exceeded under heavy loads, the following error may be observed: "address in use: connect exception". By default under Vista (when the values are not presend in the registry), the OS can allocate up to 16384 ephemeral ports above port 1024, and the OS waits for 120 seconds before reclaiming ports after an application closes the TCP connection. This is a considerable improvement over older Windows versions. However, if necessary, the following registry values can be added/edited:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters
MaxUserPort=65535 (DWORD, not in the registry by default. Recommended: leave at default, or use a number above 16384 up to 65535 decimal as necessary) - maximum number of ports to use. 1024 is automatically subtracted from entered value to allow for reserved ports under 1024.
TcpTimedWaitDelay=30 (DWORD, 0xffffffff in registry by default. Recommended: 30 decimal, denoting 30 seconds) - time to wait before reclaiming ports, in seconds. Default time before reclaiming ports, if value is at 0xffffffff or not present in the registry is 120 seconds. Just reducing the delay is often sufficient without changing MaxUserPort, as it allows for reusing ports more efficiently.

Ephemeral ports can be checked and changed using netsh as well.

To query the current values, in command prompt, type:
netsh int ipv4 show dynamicportrange tcp (for UDP, use the same command, replacing only "tcp" with "udp" at the end)

To set both the starting, and max user port using netsh, in elevated command prompt run:
netsh int ipv4 set dynamicportrange protocol=tcp start=1025 num=64511 (start=NNN denoting the starting port, and num=NNN denoting the number of ports)

Notes:
By default, dynamic ports are allocated between ports 49152 and 65535 (for a total of 16384 ephemeral ports).
Using netsh allows to set both the starting port and port range. Editing the Registry allows for setting the port range, and the starting port is fixed at 1025. Deleting the MaxUserPort registry entry (or setting it to a value outside the allowed range) causes the OS to revert to using the default values.
Some system processes can install port filters to block certain port ranges. If ephemeral ports run into these filtered port ranges, TCP/IP applications will be unable to bind to any ports.



QoS Reserved Bandwidth

As with Windows XP, nework adapters have a "QoS Packet Scheduler" enabled by default, which reserves 20% of bandwidth by default for QoS applications that request priority traffic. Note this only has effect in the presence of running QoS applications that request priority traffic. Registry value is undocumented for the Vista version of Windows. To customize this setting, in the Windows Registry:

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Psched
NonBestEffortLimit=0 (DWORD, not present in the registry by default. Recommended: 0 , possible values between 0 and 100) - indicates the percentage value of reserved bandwidth for QoS applications. Set to 0 to disable.

Notes: This tweak applies only to Windows versions that have Qos Packet Scheduler enabled. It will ONLY have effect in the presense of running QoS applications.



Gaming Tweak - Disable Nagle's algorithm

The tweak below allows for tweaking or disabling Nagle's alogrithm. Disabling "nagling" allows for very small packets to be transferred immediately without delay. Note that disabling Nagle's algorithm is only recommended for some games, and it may have negative impact on file transfers/throughput. The dafault state (Nagling enabled) improves performance by allowing several small packets to be combined together into a single, larger packet for more efficient transmission. While this improves overall performance and reduces TCP/IP overhead, it may briefly delay transmission of smaller packets. Keep in mind that disabling Nagle's algorithm may have some negative effect on file transfers, and can only help reduce delay in some games. To implement this tweak, in the registry editor (Start>Run>regedit) find:

This setting configures the maximum number of outstanding ACKs in Windows XP/2003/Vista/2008:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{NIC-id}
There will be multiple NIC interfaces listed there, for example: {1660430C-B14A-4AC2-8F83-B653E83E8297}. Find the correct one with your IP address listed. Under this {NIC-id} key, create a new DWORD value:
TcpAckFrequency=1 (DWORD value, 1=disable, 2=default, 2-n=send ACKs if outstanding ACKs before timed interval. Setting not present by default).

For gaming performance, recommended is 1 (disable). For pure throughput and data streaming, you can experiment with values over 2. If you try larger values, just make sure TcpAckFrequency*MTU is less than RWIN, since the sender may stop sending data if RWIN fills witout acknowledgement.

Also, find the following key (if present):
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSMQ\Parameters
Add a new DWORD value:
TCPNoDelay=1 (DWORD value, 0 to enable Nagle's algorithm, 1 to disable, not present by default)

To configure the ACK interval timeout (only has effect if nagling is enabled), find the following key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{NIC-id}
TcpDelAckTicks=0 (DWORD value, default=2, 0=disable nagling, 1-6=100-600 ms). Note you can also set this to 1 to reduce the nagle effect from the default of 200ms without disabling it.

Notes:
Reportedly, the above gaming tweak (disabling nagle's algorithm) can reduce WoW (World of Warcraft) latency by almost half!
XP/2003 needs hotfix or SP2 for it to work (MS KB 815230)
Vista needs hotfix or SP1 for it to work (MS KB 935458)

Information about the TCP Chimney Offload, Receive Side Scaling, and Network Direct Memory Access features in Windows Server 2008

Information about the TCP Chimney Offload, Receive Side Scaling, and Network Direct Memory Access features in Windows Server 2008: "TCP Chimney Offload, Receive Side Scaling (RSS), and Network Direct Memory Access (NetDMA) features that are available for the TCP/IP protocol in Windows Server 2008."

Re-register WSUS Client with Powershell

I went ahead and coded this using PowerShell. But I find that using WMI in PowerShell I think I seem to have more failures. But I did not take the time to confirm that suspicion.

$server = 'MACHINE-NAME'
 
#net stop wuauserv
$svc = Get-WmiObject Win32_Service -ComputerName $server -Filter "name='wuauserv'"
    if ($svc.started -eq $true) {
        write-host $server "stopping wuauserv"
        $svc.StopService()
    }
    if ($svc.started -eq $false) {
        write-host $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-host $server "Backup Registry RESULT=" $result.returnvalue
 
#Cleanup Registry
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $server)
$regKey = $reg.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate', $true)
$regKey.DeleteSubKey('AccountDomainSid')
$regKey.DeleteSubKey('PingID')
$regKey.DeleteSubKey('SusClientId')
$regKey = $reg.OpenSubKey('SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update', $true)
$regKey.DeleteSubKey('LastWaitTimeout')
$regKey.DeleteSubKey('DetectionStartTime')
$regKey.DeleteSubKey('NextDetectionTime')
$regKey.DeleteSubKey('AUState')
 
write-host $server "WSUS Reg Clean Completed"
 
#net start wuauserv
$svc = Get-WmiObject Win32_Service -ComputerName $server -Filter "name='wuauserv'"
$svc.StartService()
    if ($svc.started -eq $true) {
        write-host $server "wuauserv started"
    }
 
#RESET WUAUCLT
$result=([WmiClass]"\\$server\ROOT\CIMV2:Win32_Process").create("wuauclt /resetauthorization /detectnow")
write-host $server "wuauclt reset RESULT=" $result.returnvalue

“The LastLogonTimeStamp Attribute” – “What it was designed for and how it works” - Ask the Directory Services Team - Site Home - TechNet Blogs

“The LastLogonTimeStamp Attribute” – “What it was designed for and how it works” - Ask the Directory Services Team - Site Home - TechNet Blogs: "It is important to note that the intended purpose of the lastLogontimeStamp attribute to help identify inactive computer and user accounts. The lastLogon attribute is not designed to provide real time logon information. With default settings in place the lastLogontimeStamp will be 9-14 days behind the current date."

Scintilla and SciTE

Scintilla and SciTE: "A free source code editor for Win32"
I need to try this out. It supports Regular Expressions. I like Textpad for this feature too: www.textpad.com.

Top 10 Tips for Using Windows PowerShell - O'Reilly Media

Top 10 Tips for Using Windows PowerShell - O'Reilly Media: "Since .NET includes powerful regular expression capabilities, PowerShell includes a regex type. Just put the word regex in brackets ([]) before a string to create a regular expression. Then you can use the regular expression with the -match operators. Here's an example:

PS C:\> $re = [regex]'abc[123]'
PS C:\> 'abc1' -match $re
True
PS C:\> 'abc4' -match $re
False
PS C:\>"

Last Logon Date

# PSLastLogon.ps1
# PowerShell script to determine when each user in the domain last
# logged on.
#
# ----------------------------------------------------------------------
# Copyright (c) 2011 Richard L. Mueller
# Hilltop Lab web site - http://www.rlmueller.net
#
# This program queries every Domain Controller in the domain to find the
# largest (latest) value of the lastLogon attribute for each user. The
# last logon dates for each user are converted into local time. The
# times are adjusted for daylight savings time, as presently configured.
 
Trap {"Error: $_"; Break;}
 
$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"
 
$Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
$Searcher.PropertiesToLoad.Add("distinguishedName") > $Null
$Searcher.PropertiesToLoad.Add("lastLogon") > $Null
 
# Create hash table of users and their last logon dates.
$arrUsers = @{}
 
# Enumerate all Domain Controllers.
ForEach ($DC In $D.DomainControllers)
{
    $Server = $DC.Name
    $Test = $Server -replace "\..*$",""
    $Test = $Test.ToUpper()
    $Test
  if (!($Test.startswith("SECDC02"))) {
    $Searcher.SearchRoot = "LDAP://$Server/" + $Domain.distinguishedName
    $Results = $Searcher.FindAll()
    ForEach ($Result In $Results)
    {
        $DN = $Result.Properties.Item("distinguishedName")
        $LL = $Result.Properties.Item("lastLogon")
        If ($LL.Count -eq 0)
        {
           $Last = [DateTime]0
        }
        Else
        {
            $Last = [DateTime]$LL.Item(0)
        }
        If ($Last -eq 0)
        {
            $LastLogon = $Last.AddYears(1600)
        }
        Else
        {
            $LastLogon = $Last.AddYears(1600).ToLocalTime()
        }
        If ($arrUsers.ContainsKey("$DN"))
        {
            If ($LastLogon -gt $arrUsers["$DN"])
            {
                $arrUsers["$DN"] = $LastLogon
            }
        }
       Else
        {
            $arrUsers.Add("$DN", $LastLogon)
        }
    }#foreach
  }#if
}#foreach
 
# Output latest last logon date for each user.
$Users = $arrUsers.Keys
ForEach ($DN In $Users)
{
    $Date = $arrUsers["$DN"]
    "$DN;$Date"
}

How to get your host talking with your Virtual Machine with Virtual Server 2005 R2 « Matthew Cosier’s Blog

MS Virtual Server 2005 R2: "How to get your host talking with your Virtual Machine with Virtual Server 2005 R2"

Filtering DSCP

Filtering DSCP
The second byte in the IPv4 header (aka “those bits you’ve probably never, ever looked at”) is used for Differentiated Services, or DiffServ. It’s split into two parts: the 6 most significant bits define the DSCP (differentiated services code point) and the two least significant bits are for ECN (explicit congestion notification). You can use DSCP to divide your traffic into different classes. For example, Asterisk might use the following DiffServ value, which corresponds EF (Expedited Forwarding):
DSCP ECN
10111000
If your networking equipment is sufficiently aware, this traffic will receive preferential treatment."
Wireshark Blog

http://sourceforge.net/projects/krut/

Krut Computer Recorder
This screencast tool records audio and video from your computer screen into .mov-files and .wav-files. It could also be used to record streaming video and audio.
http://sourceforge.net/projects/krut/

VMware Site Recovery Manager Service Account | Jeremy Waldrop's Blog

VMware Site Recovery Manager Service Account | Jeremy Waldrop's Blog: "VMware Site Recovery Manager Service Account"
This would have been nice to know before reinstalling it.

4/22/2011

DHCP Client Behavior - Microsoft Enterprise Networking Team - Site Home - TechNet Blogs

DHCP Client Behavior - Microsoft Enterprise Networking Team - Site Home - TechNet Blogs: "To disable APIPA, set the following registry key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\adapter_name (for the specific adapter)

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters (for all adapters)

IPAutoconfigurationEnabled: REG_DWORD

0 – APIPA disabled

1 – default"

When a DHCP server is unavailable on a Windows Vista-based computer, Windows Vista uses an APIPA IP address much sooner than Windows XP does under the same circumstances

When a DHCP server is unavailable on a Windows Vista-based computer, Windows Vista uses an APIPA IP address much sooner than Windows XP does under the same circumstances: "This behavior occurs if Windows Vista cannot immediately contact a DHCP server. In this situation, Windows Vista tries for only six seconds to contact a DHCP server and then uses an APIPA IP address. Then, Windows Vista continues trying to acquire an IP address from a DHCP server."

DHCP Client Behavior - Microsoft Enterprise Networking Team - Site Home - TechNet Blogs

DHCP Client Behavior - Microsoft Enterprise Networking Team - Site Home - TechNet Blogs: "A registry key to control this is: AutonetRetries which may be placed as a DWORD in:

HKLM\SYSTEM\CurrentControlSet\Services\Dhcp\Parameters

OR

HKLM\SYSTEM\CurrentControlSet\Services\tcpip\Parameters

AutonetRetries controls the: 'DEBUG_LEASE [0]0430.0910::10/14/2008-20:59:41.244 (ReObtainInitialParameters:protocol_c3191)Sleeping for 275 seconds' time period

Thus if the registry is set to 30 (decimal) for example, then the sleep time is reduced to 30 seconds. This means that the set of 4 tries will be sent out every 30 seconds.

Also another interesting reference is:

KB 928233 – Windows Vista cannot obtain an IP address from certain routers or from certain non-Microsoft DHCP servers

Another registry key suggested here is DhcpConnEnableBcastFlagToggle

Though the purpose of this registry is completely different, on closer inspection, this setting has a side effect in Windows Vista where it sends out 2 sets of DISCOVER packet sets like Windows XP, albeit one set with and the second set without the Broadcast flag. Subsequent sets will be controlled by the AutonetRetries setting (300 seconds by default)."

DHCP Client Behavior - Microsoft Enterprise Networking Team - Site Home - TechNet Blogs

DHCP Client Behavior - Microsoft Enterprise Networking Team - Site Home - TechNet Blogs: "Thus, if we consider the first DISCOVER packet at 0 seconds, then 4 packets are sent out as:
0th second - 1st packet with 5 sec timeout
5th second - 2nd packet with 7 sec timeout
12th sec: 3rd packet with 15 sec timeout
27th sec: 4th packet with 32 sec timeout

The above 4 packets with a final timeout of about 1 minute may be considered as a “set” for the purpose of this discussion.

In Windows Vista: One such set is sent out every 5 minutes as can be seen above. After one set, the DHCP client sleeps for 275 seconds or over 4.5 minutes."

TRACE:
DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:58:42.943 (SendDhcpMessage:dhcpmsg_c268)Sent message to 255.255.255.255:
DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:58:42.943 (ObtainInitialParameters:protocol_c2204)Sent DhcpDiscover Message.
DEBUG_TRACE [0]0430.0910::10/14/2008-20:58:42.943 (ObtainInitialParameters:protocol_c2212)Waiting for Offer: 5 seconds
DEBUG_TRACE [0]0430.0910::10/14/2008-20:58:42.943 (TryReceive:dhcpmsg_c471)Select: waiting for: 5 seconds

DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:58:47.304 (ObtainInitialParameters:protocol_c2222)Dhcp offer receive Timeout.

DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:58:47.304 (SendDhcpMessage:dhcpmsg_c268)Sent message to 255.255.255.255:
DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:58:47.304 (ObtainInitialParameters:protocol_c2204)Sent DhcpDiscover Message.
DEBUG_TRACE [0]0430.0910::10/14/2008-20:58:47.304 (ObtainInitialParameters:protocol_c2212)Waiting for Offer: 7 seconds
DEBUG_TRACE [0]0430.0910::10/14/2008-20:58:47.304 (TryReceive:dhcpmsg_c471)Select: waiting for: 7 seconds

DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:58:54.184 (ObtainInitialParameters:protocol_c2222)Dhcp offer receive Timeout.

DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:58:54.184 (SendDhcpMessage:dhcpmsg_c268)Sent message to 255.255.255.255:
DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:58:54.184 (ObtainInitialParameters:protocol_c2204)Sent DhcpDiscover Message.
DEBUG_TRACE [0]0430.0910::10/14/2008-20:58:54.184 (ObtainInitialParameters:protocol_c2212)Waiting for Offer: 15 seconds
DEBUG_TRACE [0]0430.0910::10/14/2008-20:58:54.184 (TryReceive:dhcpmsg_c471)Select: waiting for: 15 seconds

DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:59:09.815 (ObtainInitialParameters:protocol_c2222)Dhcp offer receive Timeout.

DEBUG_PROTOCOL [1]0430.0910::10/14/2008-20:59:09.815 (SendDhcpMessage:dhcpmsg_c268)Sent message to 255.255.255.255:
DEBUG_PROTOCOL [1]0430.0910::10/14/2008-20:59:09.815 (ObtainInitialParameters:protocol_c2204)Sent DhcpDiscover Message.
DEBUG_TRACE [1]0430.0910::10/14/2008-20:59:09.815 (ObtainInitialParameters:protocol_c2212)Waiting for Offer: 32 seconds
DEBUG_TRACE [1]0430.0910::10/14/2008-20:59:09.815 (TryReceive:dhcpmsg_c471)Select: waiting for: 32 seconds

EBUG_PROTOCOL [0]0430.0910::10/14/2008-20:59:41.243 (ObtainInitialParameters:protocol_c2222)Dhcp offer receive Timeout.

DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:59:41.243 (ObtainInitialParameters:protocol_c2510)121(ERROR_SEM_TIMEOUT)
DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:59:41.243 (DhcpSetRcvAllMode:protocol_c3941)RcvAll: 0
DEBUG_PROTOCOL [0]0430.0910::10/14/2008-20:59:41.243 (ReObtainInitialParameters:protocol_c3111)Autoconfiguring....
DEBUG_TRACE [0]0430.0910::10/14/2008-20:59:41.243 (ReObtainInitialParameters:protocol_c3153)Ready to acquire autonet address. Notifying NLA...

DEBUG_LEASE [0]0430.0910::10/14/2008-20:59:41.244 (ReObtainInitialParameters:protocol_c3191)Sleeping for 275 seconds.

DHCP Client Behavior

DHCP Client Behavior - Microsoft Enterprise Networking Team - Site Home - TechNet Blogs
in situations where a DHCP Server fails or is not available, client behavior needs to be understood for efficient use. Then there are cases where a laptop user roams between his house (static IP) and office (DHCP) and does not want to keep changing the TCPIP properties every time.

First, let’s understand DHCP client behavior when DHCP server is not available. To understand well, we will observe the etl trace taken on a DHCP client. Ref: http://technet.microsoft.com/en-us/library/cc731630.aspx - “netsh dhcp client trace enable”. Etl tracing is saved as the following files: %windir%\system32\logfiles\WMI\dhcpcsvc.etl, dhcpcsvc6.etl and dhcpqec.etl.

4/18/2011

OpsMgr/SCOM 2007 R2 Implementation and Administration Best Practices – Toolzz.com

OpsMgr/SCOM 2007 R2 Implementation and Administration Best Practices – Toolzz.com OpsMgr/SCOM 2007 R2 Implementation and Administration Best Practices General Always run 64 bits hardware, OS and 64bits SQL Be sure to have enough bandwidth for core OpsMgr components and agents. Virtualization is supported on all OpsMgr roles but don’t cluster the Root Management server virtual. Snapshot backup is not supported for disaster recovery Operational Database Limit the number of consoles sessions to less than 50 Configure the SQL OpsMgrDB to use simple recovery unless you plan to use log shipping Be sure to have quick disks because of extensive I/O usage When using multi clustering be sure the connection is very fast because of disk latency Database grooming, don’t increase the default 7 days RMS (Root Management server) Never connect agents directly to the Root Management Server Never connect gateway servers directly to the Root Management Server The Root Management Server is most critical in RAM followed by CPU Limit console connections and SDK clients (webconsole, third party tools) Do not run the console on the RMS Never put the RMS in Maintenance Mode Management server Management servers talks to Root Management Servers but writes directly to OpsMgrDB Keep them close to the Root Management Server, OpsMgrDb, OpsMgrDW because of latency Memory and CPU Gateway Server (remote office) Data compression by almost 50% Dedicated management server for all gateways when using a large number of agents (R2 will support 1500) Console Use Clear the console cache /clearcache only when you have console issues Reporting Datawarehouse Limit the number of users who can generate reports Separate the SQL Data files from the transaction logs onto different disk array’s Get a DR plan Be sure you have a Disaster Recovery plan with DB and encryption key backup and test this.

System Center Operations Manager 2007 Tools & Utilities

System Center Operations Manager 2007 Tools & Utilities Important Link

4/07/2011

Dealing with WMI Timeouts « Use PowerShell

Dealing with WMI Timeouts « Use PowerShell: "The timeout value is a System.TimeSpan object. You can specify the value with a TimeSpan object, a number of ticks, or a string that can be cast to a TimeSpan.

It can be set like this:

$wmi = [wmi]”

$wmi.psbase.options.timeout =’0:0:2′ #String that will be cast to a two second TimeSpan"

3/28/2011

WSUS Client Troubleshooting - Getting Serious

Tons of good stuff here: wsuswiki.com

I found several VM's that weren't deployed properly (Geez SYSPREP for petes sake!!!!!)

I'm probably just going to run the following on all 400 of them just to be sure:

psexec @list.txt -u administrator -C c:\rereg.bat
Which references the following that must be on c:\ of the machine where the above is run:

@echo off
net stop wuauserv
REG DELETE "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate" /v AccountDomainSid /f
REG DELETE "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate" /v PingID /f
REG DELETE "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate" /v SusClientId /f
REG DELETE "HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v LastWaitTimeout /f
REG DELETE "HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v DetectionStartTime /f
REG DELETE "HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v NextDetectionTime /f
REG DELETE "HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v AUState /f
net start wuauserv
wuauclt /resetauthorization /detectnow 

Auto Logon

HKEY_LOCAL_MACHINE>SOFTWARE>Microsoft>Windows NT>CurrentVersion>Winlogon
AutoAdminLogon REG_SZ 1
DefaultUserName REG_SZ [userid]
DefaultPassword REG_SZ [password]

WSUS Client Troubleshooting

From Technet

Test all the following from the client machine.
- Check network communications with server
- ping WSUS-Server
- http://WSUS-Server[:port] - should get response - e.g. Under Construction
- http://WSUSServerName/selfupdate/wuident.cab
- Should result in offer to download a file - hit cancel
- if not, go to this URL: Check Self-Update Tree
- Check Automatic Update Client
- Open CMD prompt and type
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate
- Should display something like:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate
WUServer    REG_SZ  http://WSUSServerName
WUStatusServer      REG_SZ  http://WSUSServerName
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU
- Reset Automatic Update Client
- Open CMD prompt and type wuauclt.exe /resetauthorization /detectnow
- Wait 10 minutes
- Check C:\Windows\WindowsUpdate.log
- Check "All Computers" group on the WSUS Server to see if it appears.

3/27/2011

Powershell: Remove inactive accounts

For every machine account listed in a file, remove machine accounts from all groups and then remove the machine accounts.
$ds = new-object directoryServices.directorySearcher 
 
$names = get-content remove.txt
"------------------------------"
foreach ( $account in $names  ) {
    $account
    $ds.filter = "(&(objectCategory=computer)(objectClass=user)(name=$account))" 
    $dn = $ds.findOne() 
    if ($dn) {
           #remove computer from groups
           $user = [ADSI]$dn.path 
           "  Removed from groups:"
     foreach ($group in $user.memberof)
       {
       $groupDE = [ADSI]"LDAP://$group" 
       "    "+$groupDE
       $groupDE.remove("LDAP://$($user.distinguishedName)")  
       }

     #remove computer account
     $old = $user.distinguishedname -replace ',.*$',''
     $olduser = $old -replace 'CN=',''
     $usr = $($olduser).tolower()
     $usr + " removed from AD"             
     $location = $dn.path -replace "$old,",''
     $ou = [ADSI]$location
     $ou.delete("computer","cn=$usr")
 }#if
"------------------------------"
}#foreach

Powershell: Report Server Group Membership

Create an HTML report of each server in AD and its group memberships.

###########################################################################
#
#    server-group.ps1
#
#    Report group membership for each Windows Server in AD
#
###########################################################################

# Create $list of AD machine accounts for Windows Servers 
$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) { $list = $list + $Server } #skip a null value
    }#foreach
 
# Prepare output file
"<HTML>" | out-file server-groups.html
"<HEAD>" | out-file server-groups.html -append
"<TITLE></TITLE>" | out-file server-groups.html -append
"</HEAD>" | out-file server-groups.html -append
'<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#FF0000" VLINK="#800000" ALINK="#FF00FF" BACKGROUND="?">' | out-file server-groups.html -append
"<H1>Servers' Group Membership</H1>" | out-file server-groups.html -append
 
foreach ($target in $list) {
    $ds = new-object directoryServices.directorySearcher 
    $ds.filter = "(&(objectCategory=computer)(objectClass=user)(name=$target))" 
    $dn = $ds.findOne() 
    if ($dn) { #found
        $user = [ADSI]$dn.path 
        $userDE = [ADSI]"LDAP://$($user.distinguishedname)" 
        $user.name
        "<b>" + $user.name + "</b><BR>" | out-file server-groups.html -append
        $groups = $user.memberof
        foreach($group in $groups) {
            $strGroup = $group.split(',')[0]
            $strGroup = $strGroup.split('=')[1] 
            "     "+$strGroup
            "        " + $strGroup + "<BR>" | out-file server-groups.html -append
            }#foreach
        }#if
    }#foreach
"</BODY></HTML>" | out-file server-groups.html -append

###########################################################################

Powershell: Import Group Members

This script will be used to import a file of the same format that I export from the previous post. After using Excel to review and change the listings. I use these group memberships to filter group policy permissions to apply WSUS client settings to servers.

############################################################################
#
# IMPORT-SERVER-GROUP.PS1
#
# Assign servers to WSUS group from CSV file.  
# Note:  removes server from any existing groups that contain WSUS
#
# CSV Format:  (include headings)
#
#  Server, Group
#  SERVER01, WSUS Test Group
#
############################################################################

$list = @(Import-Csv WSUS-TEST.CSV)
$today = get-date

"==========================================================================="
" CHANGE LOG - " + $today

foreach ( $item in $list ) {
 $account = $item.Server;
 $target = $item.Group;

"---------------------------------------------------------------------------"
 "    " + $account

#Find computer object and remove it from groups
 $ds = new-object directoryServices.directorySearcher 
 $ds.filter = "(&(objectCategory=computer)(objectClass=user)(name=$account))" 
 $dn = $ds.findOne() 
 if ($dn) { #found
  #remove computer from groups
  $user = [ADSI]$dn.path 
  "      Removed from groups:"
  foreach ($group in $user.memberof)
   {
   $groupDE = [ADSI]"LDAP://$group" 
   "        "+$group
   if ($strGroup -match "WSUS") {
    $groupDE.remove("LDAP://$($user.distinguishedName)")  
    }#if
   }#foreach
 }#if

$dn=0;

#Find group object and add server to it
 $ds = new-object directoryServices.directorySearcher 
 $ds.filter = "(&(objectClass=Group)(name=$target))" 
 $dn = $ds.findOne() 
 if ($dn) { #found Group
  $group = [ADSI]$dn.path 
  $groupDE = [ADSI]"LDAP://$($group.distinguishedname)" 
  $ds.filter = "(&(objectCategory=computer)(objectClass=user)(name=$account))" 
  $dn = $ds.findOne()
  if ($dn) { #found machine account
   $usr = [ADSI]$dn.path
   $ADuser = [ADSI]"LDAP://$($usr.distinguishedname)"
   "      Added to " + $target
   $groupDE.add("LDAP://$($ADuser.distinguishedName)")  
   }#if
 }#if
}#foreach
"==========================================================================="
############################################################################

Powershell: Export Group Membership

Putting the pieces together
This post pulls together some of my previous fragments into something more specifically useful.

###########################################################################
#
#  server-group.ps1
#
#       Export group membership for each Windows Server in AD
#              if the group name contains WSUS
#
###########################################################################

#delete output file if it exists
if ( test-path wsus-server-groups.csv ) { remove-item wsus-server-groups.csv }

# Create $list of AD machine accounts for Windows Servers 
$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) { $list = $list + $Server } #skip a null value
    }#foreach
"Server, Group" | out-file -encoding ASCII  wsus-server-groups.csv # output headings
foreach ($target in $list) {
    $ds = new-object directoryServices.directorySearcher 
    $ds.filter = "(&(objectCategory=computer)(objectClass=user)(name=$target))" 
    $dn = $ds.findOne() 
    if ($dn) { #found
       $user = [ADSI]$dn.path 
       $userDE = [ADSI]"LDAP://$($user.distinguishedname)" 
       $user.name
       $groups = $user.memberof
       foreach($group in $groups) {               {
           $strGroup = $group.split(',')[0]
           $strGroup = $strGroup.split('=')[1] 
           "     "+$strGroup
           if ($strGroup -match "WSUS") {
               $Target+", "+$strGroup | out-file -encoding ASCII  wsus-server-groups.csv -append
               }#if
           }#foreach
    }#if
}#foreach
###########################################################################

Powershell: List AD Group Membership


###########################################################################
#
#    List AD Group Membership of a user in specified OU
#
###########################################################################
$root=([adsi]"").distinguishedName
$ou=[adsi]("LDAP://ou=Engineering,ou=Chicago,ou=Information Technology,"+$root)
$user=$ou.psbase.children.find("cn=Smith\, Billy")
$groups = $user.memberof
foreach($group in $groups){
    $strGroup = $group.split(',')[0]
    $strGroup = $strGroup.split('=')[1]
    $strGroup
    }#foreach
###########################################################################

Group Policy Notes

"Stream of conciousness" notes on Group Policies

FWIW

- either the computer settings or the user settings get applied, not both -- as one might expect.
- e.g. logging on machine in TRAINING OU - only the computer settings are applied (since user object is in another OU.)
- when appropriate - disable user or computer portion -- whichever doesn't apply.
- GP can link to domain, site, OU, local
- cannot be applied to container (e.g. builtin, computers, users)
- avoid using site GPO's.
- order of application: Local, Site, Domain, OU
- GPO components: GP Container, GP Template
- Advertise application = allows install from add/remote programs. (Publish = do the install automatically.)
-start-run dssite.msc, domain.msc, dnsmgmt.msc, winsmgmt.msc
- sysvol\[domain]\Policies (templates) - (must match) AD System\Policies container
- GUID's are universal.
- Other paths to GPT - group policy templates - both of the below point to the exact same location

c:\windows\sysvol\domain\policies

c:\windows\sysvol\sysvol\[domain]\policies
- When working directly with GPT's always use: c:\windows\sysvol\domain\policies
- GPC replicates with AD. GPT's replicate via RPC with FRS or DFSR (in 2008AD functional level)
- In 2003, ADSIEDIT shows properties and replication status of policies.
- ADM folder on sysvol is not necessary, access to them from somewhere is needed when administering.
- a copy of this folder is made for every policy - this is the vast majority of the space consumed for policies on sysvol
- versions - bit 5 from right is incremented when user policy is changed, bit 1 is incremented when computer policy is changed.
- do NOT disable default domain policy and make your own domain policy.

- If you copy the default domain policy and disable the default domain policy and work from the copy "works" but some software looks for the GUID for adjusting.
- just leave the default domain policy blank and create another policy.
- SYSVOL replication can use DFSR in 2008 functional level domain. Requires running DFSRMIG.EXE

- Local policies are saved in: c:\windows\system32\GroupPolicy
- gPLink points to the GPC, GPC points to GPT
- GPC stores version number in "VersionNumber" attribute of the GPO.
- GPT stores version number in GPT.INI file
- utility named GPOTOOL can help identify issues or problems.
- refresh interval
- DC's - 5 minutes
- Others - 90-120 minutes
- run GPRESULT /V - shows what happened last time policy was applied - uses RSOP which requires read permission for domain.

- ADPREP /DOMAINPREP /GPPREP -> sets permissions.
- Restore Domain Policies to default and resets ACLs - caution! Find KB article for caveats.
- DCGPOFIX.EXE - Win2003 & later
- RECREATEDEFPOL.EXE - Win2000
- Templates

- ADM - pre-Vista - language specific - required for each policy
- ADMX - based on XML - Vista & later
- ADML files - associated with an ADMX file - language specific portion of template.
- c:\windows\PolicyDefinitions on Vista and later machines.

- GPMC - Group Policy Management Console
- v1 - Windows XP, 2003
- v2 - Vista and later
- administer from one or the other not both.
- Go into GPMC and backup GPO's!!!!!!!!!!!!!!!!!!!!!!!!!!!
- custom ADM files must be imported.

- Using a Central Store of ADMX files: KB929841

PING test

PowerShell to PING a list of computers.

##########################################################################
# 
#    PING List of Machines
#
##########################################################################

$computers = get-content list.txt
$ping = new-object system.net.networkinformation.ping
$pingreturns = @()
foreach ($entry in $computers) {
  $entry = $entry -replace "\s{2,}", ""
  if ($entry.length -eq 0) {$entry = 'NOTHING'}
  $result = $entry+" "+(Test-Connection -ComputerName $entry -quiet -count 1)
  $result
  $result | out-file -encoding ASCII -filepath RESULT.TXT -append
  }#foreach

E-mail to Cell Phone

Here's a reference of how to e-mail someone's cell phone if you know who their cell provider is:
Verizon ........ 10digitphonenumber@vtext.com
     AT&T ........... 10digitphonenumber@txt.att.net
     Sprint ......... 10digitphonenumber@messaging.sprintpcs.com
     T-Mobile ....... 10digitphonenumber@tmomail.net
     Nextel ......... 10digitphonenumber@messaging.nextel.com
     Cingular ....... 10digitphonenumber@cingularme.com
     Virgin Mobile .. 10digitphonenumber@vmobl.com
     Alltel ......... 10digitphonenumber@message.alltel.com
     CellularOne .... 10digitphonenumber@mobile.celloneusa.com
     Omnipoint ...... 10digitphonenumber@omnipointpcs.com
     Qwest .......... 10digitphonenumber@qwestmp.com
     Metro PCS ...... 10digitphonenumber@mymetropcs.com

E-Mail to Cell Phones

If you know somebody's cell phone provider you can send them a text via e-mail.
Verizon:       10digitphonenumber@vtext.com
AT&T:          10digitphonenumber@txt.att.net
Sprint:        10digitphonenumber@messaging.sprintpcs.com
T-Mobile:      10digitphonenumber@tmomail.net
Nextel:        10digitphonenumber@messaging.nextel.com
Cingular:      10digitphonenumber@cingularme.com
Virgin Mobile: 10digitphonenumber@vmobl.com
Alltel:        10digitphonenumber@message.alltel.com
CellularOne....10digitphonenumber@mobile.celloneusa.com
Omnipoint......10digitphonenumber@omnipointpcs.com
Qwest..........10digitphonenumber@qwestmp.com
Metro PCS......10digitphonenumber@mymetropcs.com 

Powershell: List AD Machine Accounts


######################################################################
#
# List all Windows Servers with machine accounts in Active Directory
#
######################################################################

$ServerList = 'c:\allservers.txt'
New-Item $serverlist -Type file -Force >$nul

$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 "\.US\.DOMAIN\.COM", ""
  write-output $Server | out-file -encoding ASCII -filepath $ServerList -append
  }#foreach

Powershell: List the members of a group


$root=([ADSI]"").distinguishedName
$Group = [ADSI]("LDAP://CN=Domain Admins,CN=Users,"+$root)
$Group.member

Powershell Text Output Mystery

One night I spent a good while puzzling over why my text output from a powershell script wasn't working when I opened it in excel as CSV.
It looks beautiful in TextPad and Notepad. I went down the garden path for a little while when I noticed that when I edited some aspects of my record format and saved the file from the editor it opened perfectly in Excel. So I made changes to my script to reformat the output but it had the same problem. And then I noticed that it didn't matter if I changed anything in the editor, all I had to do was save it from the editor and my problem was magically solved.
This led me to open it in HEX edit mode and found some ponderous bytes at the beginning of my file: "FF EE". A little googling led me to the answer.
By default powershell adds a “byte order mark” to the beginning of it's output. See WikiPedia
Use: out-file -encoding ASCII to prevent this from happening.

Speed Up Internet Explorer

Do more than 2 things at once in Internet Explorer:
http://support.microsoft.com/kb/282402
To increase the number of files that you can download at one time to 10, follow these steps:
  1. Start Registry Editor.
  2. Locate the following key in the registry: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings
  3. On the Edit menu, point to New, click DWORD Value, and then add the following registry values:
    Value name: MaxConnectionsPer1_0Server
    Value data: 10
    Base: Decimal
    Value Name: MaxConnectionsPerServer
    Value data: 10
    Base: Decimal
  4. Exit Registry Editor.
For Internet Explorer 8.0
How to configure the connection limit by modifying a registry key
Start Registry Editor.

  1. Locate the following key in the registry:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_MAXCONNECTIONSPERSERVER
  2. On the Edit menu, point to New, click DWORD Value, and then add the following registry values:  
  3. Value name: iexplore.exe
    Value data: 10
    Base: Decimal
 
Note set this value to the connection limit that you want for HTTP 1.1 connections. By setting the value to 10, you increase the connection limit to 10.
 
  1. Locate and then click the following registry subkey:
    HEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_MAXCONNECTIONSPER1_0SERVER
  2. On the Edit menu, point to New, click DWORD Value, and then add the following registry values:
    Value name: iexplore.exe
    Value data: 10
    Base: Decimal
Note set this value to the connection limit that you want for HTTP 1.1 connections. By setting the value to 10, you increase the connection limit to 10.
Exit Registry Editor.

Which switch is which?

I couldn't remember which devices were the oldest ones in a branch office where we planned to replace some gear.
You would think that somewhere in SHOW VER there would be a manufacture date of a switch or router.
After a long time staring at various output from SHOW commands a friend of mine "googled it for me" (see LetMeGoogleThatForYou)
and came up with this helpful information:
> Anyone know how to locate the manufacturing date a switch?
Do a "show version" and locate the System Serial Number.
The serial number is in this format: LLLYYWWSSSS
LLL = location of the supplier
YY = year of manufacture
WW = week of manufacture
SSSS = serial-id
Year codes:
01 = 1997
02 = 1998
03 = 1999
04 = 2000
05 = 2001
06 = 2002
07 = 2003
08 = 2004
09 = 2005
10 = 2006
11 = 2007
12 = 2008

Antivirus Exclusions

So may times a long bout of troubleshooting with a pesky problem ends up being something obvious. It is not always obvious when virus protection is causing a problem. When I reach that first point of scratching my head saying "this doesn't make sense" I try to make a point of eliminating antivirus from the mix and testing again.
Often the software vendor will have recommendations on which of their working directories or configuration files need excluded.
Check out this great resource for Microsoft Antivirus Exclusions

iSCSI and VMWare

Some iSCSI may be in my future. Unless we jump straight to NFS.
This is a great article: VirtualGeek

Cisco IOS

We used to have to pay more for the IP Advanced version of IOS to run OSPF on our branch office core routers.
Now I am told that we can run at least one instance of OSPF in IP Base license (cheaper) when running IOS ver 12.2.55se1

AD Attributes Reference

ADSI & LDAP in scripts is very powerful, but there are so many little details to get right. There are often ways to make a script to see all your options, but sometimes it's good to be able to just look up what exactly attribute names are or see a list of them all.
Here on MSDN

Check internet routes to my network

helpful for testing:
telnet route-views.routeviews.org

3/26/2011

Powershell: Add members to AD group


$users = get-content add.txt
$target = "testGroup"
"=============================="
" ADD TO " + $target
"------------------------------"
 $ds = new-object directoryServices.directorySearcher 
 $ds.filter = "(&(objectClass=Group)(name=$target))" 
 $dn = $ds.findOne() 

 if ($dn) { #found
    $group = [ADSI]$dn.path 
    $groupDE = [ADSI]"LDAP://$($group.distinguishedname)" 

    foreach ($name in $users)
     {
     $ds.filter = "(&(objectCategory=computer)(objectClass=user)(name=$name))" 
     $dn = $ds.findOne()
     if ($dn) {
     $usr = [ADSI]$dn.path
     $ADuser = [ADSI]"LDAP://$($usr.distinguishedname)"
     "    "+$ADuser.name
      $groupDE.add("LDAP://$($ADuser.distinguishedName)")  
              }#if
        }#foreach
    }#if
"------------------------------"

3/25/2011

Powershell: Find inactive group members

Get the members each group in the list. if the members are on a list of inactive accounts, flag them in the output.

$root=([ADSI]"").distinguishedName
 
$Groups=get-content groups.txt
$Accounts=get-content inactive.txt
 
foreach ($Group in $Groups) {
    "-----------------------------------"
    $Group+":"
    $Group = [ADSI]("LDAP://CN=$Group,CN=Users,"+$root)
    $Output = $Group.member –Replace ‘\,.*$’, ‘’
    $Check = $Output -Replace 'CN=',''
    foreach ($Item in $Check) {
        $test = $Item.ToLower()
        if ($Accounts -contains $test) {
            "***************"+$test
            }
            else {
            $test
        }
    }
}

3/20/2011

Code in text box with scroll bars

The following is the CSS used in my template to quote code with <PRE> <CODE>:

pre { 
 font: 100% courier,monospace; 
 width: 100%;
 overflow-x: auto;
 max-height: 400px
 border: 1px dotted #281;
 border-left: none;
 background-color: #fff;
 padding-bottom: 16px;
 font-size: 1em;
 word-wrap: normal;
}

code { 
 font: 100% courier,monospace; 
}

3/19/2011

Powershell: RegEx

Lately I've been doing RegEx replacement with powershell instead of Perl because it has turned out to be so intuitive.
I've also had a bit of fun doing various powershell one-liners from the command line for stuff I just need to do quickly and probably don't need again. For example:

Powershell -command $allservers = get-content allservers.txt; $allservers -Replace ‘\.corp\.domain\.com’, ‘’
the above executes powershell and runs a command that reads in a file of servers' dns names and then writes to the screen the list without the domain part of their name.
Also, I often use TextPad (www.textpad.org) to use a more complicated RegEx against a file.