Friday, December 14, 2012

Powershell, WMI and IP study

So I need a function that would determine whether the last octet of an IPv4 address was even or odd. Why? Well long story short I wanted to use it as a filter on a group policy to dynamically split our servers into two groups to spread out and AV scan. The reason really doesn't matter but its an interesting code study:

I'll build up over a few line.

1. Get the configuration
 
 Get-WMIObject win32_networkadapterconfiguration
 
2. Pull out the IPAddress information
 
 Get-WMIObject win32_networkadapterconfiguration | Where {$_.IPAddress}
  
 3. Pull out just the address parts
  
Get-WMIObject win32_networkadapterconfiguration | Where {$_.IPAddress} | Select -Expand IPAddress
  
 4. Throw out the IPv6 piece
  
Get-WMIObject win32_networkadapterconfiguration | Where {$_.IPAddress} | Select -Expand IPAddress | Where{$_ -like '*.*.*.*'}
 
 5. Get the last character of the string for testing
  
(Get-WMIObject win32_networkadapterconfiguration | Where {$_.IPAddress} | Select -Expand IPAddress | Where{$_ -like '*.*.*.*'})[-1]

6. Divide by two and test for integer

((Get-WMIObject win32_networkadapterconfiguration | Where {$_.IPAddress} | Select -Expand IPAddress | Where{$_ -like '*.*.*.*'})[-1]) / 2 -is [Int]

Now this is all very well but it would have to be placed into a start-up script since it uses language beyond the scope of a GPO filter since that can only use the WQL language. Also, only server 2008 R2 and 2012 have PowerShell so you would have to convert to VBScript (booo!) There is another approach and that is to use regular expressions but the problem remains that you cannot use a WHERE clause on an IP address in WQL since the IP address is an array of strings. However, remembering the intent here is to randomly divide a GPO between two groups of servers, we can use the happenstance of their MAC addresses instead of the happenstance of their IP address, since the MAC address is a simple string.

This query would be true if it had a NIC with a MAC address of xx:xx:xx:xx:xx:x[0-7]

select * from Win32_networkadapterconfiguration WHERE IPEnabled='TRUE' AND MACAddress LIKE "%:%:%:%:%:%[0-7]"

This query would be true if it had a NIC with a MAC address of xx:xx:xx:xx:xx:x[8-F]

select * from Win32_networkadapterconfiguration WHERE IPEnabled='TRUE' AND MACAddress LIKE "%:%:%:%:%:%[8,9,A,B,C,D,E,F]"
 
Cheers!

No comments:

Post a Comment