.Net Classes within VBScript: Doing Randomness and Arrays the Easy Way

.Net and VBScript can play together
Back in 2007, the Microsoft Scripting Guys posted a article titled “Hey, Scripting Guy! Be Careful What You Say.” This article changed everything in the way I scripted because it should how simply you can access some .Net classes through COM callable wrappers. The two they focus on are “System.Random” and “System.Collections.ArrayList”.

Set objRandom = CreateObject("System.Random")
Set objArrList = CreateObject("System.Collections.ArrayList")

Read More

Webcast: Dell, Hyper-V and System Center Goodness

Removing Virtualization Barriers and Simplifying Management with A Frameless Storage Solution and Microsoft System Center

Virtualization is no longer just an IT buzzword –your customers are asking for it, and you’re ready to deliver. But with the different types of storage hardware and protocol choices in the market, are you prepared to offer the best storage option for your customer’s virtualization solution? How about keeping management and maintenance simple after deployment?

Date/Time: April 19, 2011 12 PM Pacific/ 2 PM Central / 3 PM Eastern

Sign up here: http://goo.gl/Cdpkf

Aggregate and Translate: Moving to Google Reader

For years, I have been bouncing between RSSOwl, FeedReader and FeedDemon.  I have built the ultimate feed list for the technologies, blogs and news sources I care about.  The real beauty of RSS is it enables one to quickly get up to date on news and industry trends without wasting time.  New posts are there, you pick the ones that interest you, star or share the ones you care about and ignore the rest.  While many of my peers are wasting their time hitting all their favorite sites and going page by page, I have already read it and moved on to real work.

I decided it was time to listen to a good friend and move to Google Reader.  I’ll never look back.

The killer feature that guaranteed my love for Google Reader is their translator.  The one feed I follow that has the most traffic and is most pertinent to me and my job is the Microsoft Technet Blogs‘ feed.  It includes all the technet blogs in one aggregate feed.  I have asked Microsoft over and over for a feed based on language or locality to help filter out all the non-english feeds.  All I have been told is that it is coming…  Well, they can stop working on this (assuming they actually were).

Google Reader - Translate Feed
Google Reader - Translate Feed

So, @niceguyscott sends me an e-mail of a screenshot from Google Reader.  A little option says, “Translate into my language.”  What?!?  Well, ever since I enabled that little option on the multilingual technet feed, I forgot about the fact that about a third of the posts I read are not even natively in english.  I don’t need Microsoft to give an english only option anymore.  Instead of excluding these feeds, I can now track news and trends in any tongue supported by Google Translate. (Note: This isn’t a new feature. It debuted back on Nov of ’08.)

RSS feed readers, whether desktop, mobile or web, all offer their own set of special features.  Some are sexier.  Some are minimalist.  Some have the whole kitchen sink.  Google Reader gives that functionality you need to quickly digest content, share and save what is important to you and gives you a couple killer features without getting in the way.  That has made it my new favorite.

I am excited to explore what other content I am missing due to the language barrier that technology continues to tear down.

vbScript: Quickly determine architecture

I’ve been using a routine to determine 64-bit v 32-bit workstations for some time checking the registry for the PROCESSOR_ARCHITECTURE in the HKLMSYSTEMCurrentControlSetControlSession ManagerEnvironment path. However, this was proving to be error prone. So, I just gave up that method altogether since all Windows x64 editions have a “%SystemDrive%Program Files (x86)” directory. This makes it just a quick and easy call the folderexists method of the filesystemobject.

The only downside is that can’t be used remotely but since most of my scripts are used in local policies, this shouldn’t be an issue.

Cheers!

Private Function is64bit()
	Dim filesys : Set filesys = CreateObject("Scripting.FileSystemObject")
	Dim bln64bit : bln64bit = False
	If filesys.FolderExists("C:Program Files (x86)") then bln64bit = True
	is64bit = bln64bit
End Function

Installing Java via Script and Group Policy

Due to some software requirements, there was a need to get JRE 1.5.0_09 rolled out across our enterprise. The requirements were pretty straight forward:

  • Only install on client operating systems (Windows 2000, Windows XP, Windows Vista and Windows 7)
  • Detect the versions of Java installed. If 1.5.0_09 is installed, exit.  If 1.5.0_08 or less was installed, install this version.  If it has a newer version, do nothing.

The best way of determining the Java versions is to look in %program files%.  On 64-bit machines, this is “C:program files (x86)Java”.  On 32-bit, this is “C:program filesJava”.  The script accounts for this.

I wanted to post this because several of the functions used are very useful.  The share hosting the jre runtime needs to have wide open read-only access so the Local System account can access share (Domain Computers).  This script can then be applied to machine accounts in group policy as a startup script.  If you want to test this, just comment out line 111.

Cheers!
Download Compressed (.zip) script

'======================================================
' VBScript Source File
' NAME: Java Runtime Environment Installation
' AUTHOR: Andrew J Healey
' DATE  : 2010.07.15
' COMMENT: This script will install the jre references based on processor, existing 
' 				   installations, and operating system.  This script is to be run at startup
'				   under the Local System account. No user interaction is required for 
'				   this script to work properly.
'======================================================

Option Explicit

If isClientOperatingSystem = False Then wscript.quit

Dim jreVerMajor, jreVerMinor
Dim strCommand, strPathToInstall, strInstallFile, strArguments

'============== BEGIN CONFIGURATION SECTION =================
jreVerMajor = "jre1.5.0_" 'As string
jreVerMinor = 9 'As Integer for <> operations
strPathToInstall = "\servernameSoftwareJava" 'Point to share \servernamesharefolder
strInstallFile = "jre-1_5_0_09-windows-i586-p.exe"
strArguments = "/s /v /qn ADDLOCAL=jrecore,extra IEXPLORER=1 REBOOT=Suppress JAVAUPDATE=0 SYSTRAY=0 WEBSTARTICON=0"
strCommand = strPathToInstall & strInstallFile & " " & strArguments
'============== END CONFIGURATION SECTION =================

If checkForJRE(jreVerMajor, jreVerMinor) = False Then
	Call InstallJava(strCommand)
End If

Private Function checkForJRE(ByVal jreVerMajor, ByVal jreVerMinor)
	Dim jrePath
	Dim blnMajorFound : blnMajorFound = False
	Dim blnMinorFound : blnMinorFound = False
	
	If is32bit Then
		jrePath = "C:Program FilesJava"
	Else
		jrePath = "C:Program Files (x86)Java"
	End If
	
	On Error Resume Next
		Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
		Dim objFolder : Set objFolder = objFSO.GetFolder(jrePath)
		Dim colSubfolders : Set colSubfolders = objFolder.Subfolders
		Dim objSubfolder
		
		For Each objSubfolder in colSubfolders
			If Left(objSubfolder.Name,Len(jreVerMajor)) = jreVerMajor Then
				blnMajorFound = True
				If CInt(Right(objSubfolder.Name,2)) >= jreVerMinor Then
					blnMinorFound = True
				End If
			End If
		Next
		
		If Err.Number <> 0 Then
			chechForJRE = True
			Exit Function
		End If
		
		If blnMajorFound = False And blnMinorFound = False Then
			checkForJRE = False
		Else
			checkForJRE = True
		End If
	On Error GoTo 0
	
	Set objSubfolder = Nothing
	Set colSubfolders = Nothing
	Set objFolder = Nothing
	Set objFSO = Nothing
	jrePath = Empty
	blnMajorFound = Null
	blnMinorFound = Null
	jreVerMajor = Empty
	jreVerMinor = Empty
End Function 

Private Function is32bit()
	'Get processor architecture; do not use remotely
	const HKEY_LOCAL_MACHINE = &H80000002
	Dim oReg,strKeyPath,strValueName
	Dim strValue
	On Error Resume Next
		Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\.rootdefault:StdRegProv")

		strKeyPath = "SYSTEMCurrentControlSetControlSession ManagerEnvironment"
		strValueName = "PROCESSOR_ARCHITECTURE"
		oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue

		If Err.Number <> 0 or strValue = "x86" Then
			is32bit = True
		Else
			is32bit = False
		End If
		Err.Clear
	On Error GoTo 0
	
	Set oReg = Nothing
	strKeyPath = Empty
	strValueName = Empty
End Function 

Private Function InstallJava(ByVal strCommand)
	On Error Resume Next
		Dim objWshShell, intRC

		Set objWshShell = WScript.CreateObject("WScript.Shell")
		intRC = objWshShell.Run(strCommand, 0, True)

		If intRC <> 0 Or Err.Number <> 0 Then
			InstallJava = "Failed"
		Else
			InstallJava = "Success"
		End If
	On Error GoTo 0
	Set objWshShell = Nothing
	intRC = Empty
End Function 

Private Function isClientOperatingSystem()
	Dim objWMIService, objItem, colItems
	Dim strOS

	On Error Resume Next
		' WMI Connection to the object in the CIM namespace
		Set objWMIService = GetObject("winmgmts:\.rootcimv2")

		' WMI Query to the Win32_OperatingSystem
		Set colItems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")

		' For Each... In Loop (Next at the very end)
		For Each objItem in colItems
			strOS = objItem.Caption
		Next
		
		If InStr(strOS,"Windows 7") <> 0 Or InStr(strOS,"XP") <> 0 Or InStr(strOS,"2000 Professional") <> 0 Or InStr(strOS,"Vista") <> 0 Then
			isClientOperatingSystem = True
		Else
			isClientOperatingSystem = False
		End If
		
		If Err.Number <> 0 Then isClientOperatingSystem = False
		
		strOS = Empty
		Set objItem = Nothing
		Set colItems = Nothing
		Set objWMIService = Nothing
	On Error GoTo 0
End Function 

Powershell: Getting the IP Address, FQDN and MAC Address of Each Domain Controller

I was asked to get a baseline for generating reports within AD.  The two important pieces of information which were required to generate these reports were the ip address and FQDN of each domain controller.  The script would then connect to each individual system to gather data.  While I was at it, I added the MAC Address just to see what other pieces of data would be useful out of the Win32_NetworkAdapterConfiguration class.

#Enter the fqdn of your forest/domain
$fqdn = "fully.qualified.domain.name"
#Create Empty HashTable
$ht = New-Object psobject | Select FQDN, MACAddress, IPAddress

#Enumerate Domain Controllers
$context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain",$fqdn)
$dclist = [System.DirectoryServices.ActiveDirectory.DomainController]::findall($context)
ForEach ($strComputer in $dclist) {
	#Get IP Info of each DC
	$colItems = GWMI -cl "Win32_NetworkAdapterConfiguration" -name "rootCimV2" -comp `
                $strComputer.name -filter "IpEnabled = TRUE"
	ForEach ($objItem in $colItems){
        $ht.FQDN = $strComputer
        $ht.MACAddress = $objItem.MacAddress
        $ht.IPAddress = $objItem.IpAddress
	}
    $ht
}

Powershell: Using PoSH to Search Across Multiple Domains in Forest


I was recently asked to get a quick report of all Windows 7 computers within a multi-domain AD forest.  After banging my head into the keyboard for a while, I finally figured it out.  The script below should do the trick.

Also, if you use the OperatingSystemVersion attribute, you will find that Server 2008 R2 shares version “6.1 (7600)”.  So, the best way to find Windows 7 only, is to search for “Windows 7*” with the wildcard character against the OperatingSystem attribute.  That will ensure all Windows 7 versions are returned and will exclude Server 2008 R2 from your results.

#Get Domain List
$objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
$DomainList = @($objForest.Domains | Select-Object Name)
$Domains = $DomainList | foreach {$_.Name}


#Act on each domain
foreach($Domain in ($Domains))
{
	Write-Host "Checking $Domain" -fore red
	$ADsPath = [ADSI]"LDAP://$Domain"
	$objSearcher = New-Object System.DirectoryServices.DirectorySearcher($ADsPath)
	$objSearcher.Filter = "(&(objectCategory=Computer)(operatingSystem=Windows 7*))"
	$objSearcher.SearchScope = "Subtree"

	$colResults = $objSearcher.FindAll()
	
	foreach ($objResult in $colResults)
	{
		$Computer = $objResult.GetDirectoryEntry()
		$Computer.DistinguishedName
	}
}

Part 3: Blocking Bad Hosts – Blocking Them, Easily (CLI Edition)

In part two, I showed you how to use the Local Security Policy GUI to block the bad guys. There were a lot of pretty pictures for those that prefer the GUI. In this version, I’ll show you how to accomplish the same thing from the command line. This is my preferred method.  It is much simpler to automate and explain.

By following the steps below, you will be able to create a new policy and manage the filter lists and actions. The goal here will be to put all these pieces together into a nice tidy package that is fully automated. Read More

Part 2: Blocking Bad Hosts – Blocking Them, Easily (GUI Edition)

In part two, I want to show how you can quickly setup an ipsec policy to block the bad hosts you identified in part one. While many methods can be used to block hosts, using the Local Security Policy (secpol.msc) and ipsec is a simple method which can be fully automated.

By following the steps below, you will be able to create a new policy and manage the filter lists and actions. In part three, I will explain how this can be done from the command line for all you CLI warriors. This tutorial should be accurate for: Windows XP, Vista, 7 and Server 2003, 2008, 2008R2 (possibly even 2000) Read More

Part 1: Blocking Bad Hosts – Finding Them, Easily

Download Script: get-bad-hosts.zip

While troubleshooting some issues on an OWA Front-End server, I went over to the security log to see if the authentication attempts were getting past this box. The problem I found was the log was so full of failed logon attempts it was difficult to filter out what I was looking for. In a twelve hour period, there were thousands of 529 events in the security log. Now, I know this is nothing new, but I found a few patterns. I manually exported the log to a CSV, parsed out all the source ip addresses and opened it up in Excel. What I found was that 98.7% of failed logon attempts were made by just four different ip addresses.  (I recommend using MaxMind’s GeoIP Address Locator for help in determining where the source addresses are located.) Read More