Script for listing all servers with /24 subnet - STUCK!

Hello, I am trying to write a script that will provide me with a .csv that will list the server name and subnet mask, but ONLY if the subnet mask is equal to 255.255.255.0 (/24). Ideally I would like to have this in a spreadsheet format with servers in one column and SMs in the next. I think I have just been working on this for too long today and am having “scripter’s block”. Please let me know if I can answer any other questions, here is the code I have so far. I originally had it wrapped in a function, but then decided I wanted to use Active Directory and did not want to have any command line parameters, and I didn’t know how to keep the function without having a parameter. Thanks for any help. :slight_smile:

 

# Import the Active Directory module for the Get-ADComputer CmdLet
Import-Module ActiveDirectory

    Write-Verbose "Retrieving server names from Active Directory..."

	#Retrieve a list of PSP servers from Active Directory and set to $serverNames
    $serverNames = Get-ADComputer -Filter "(Name -like '*P01') -or (Name -like '*P02')" `
									-SearchBase "OU=Server,OU=PROD,OU=POS,DC=NORDSTROM,DC=NET" ` |
					 Select-Object -ExpandProperty name | Sort-Object                
    
    Write-Verbose "Gathering network information..."

    #Iterate through each of the server names
	foreach ($serverName in $serverNames) {

			#Check if the server is online before doing the remote command
			If (Test-Connection -ComputerName $serverName -Quiet) {

                $ethernetAdapters = Get-WmiObject -ClassName Win32_NetworkAdapterConfiguration -Filter "ipenabled = 'true' and description like 'Intel(R) Ethernet%'";       

                    foreach ($ethernetAdapter in $ethernetAdapters) {

                        $SubnetMask  = $ethernetAdapter.IPSubnet[0];

                            If ($SubnetMask -eq "255.255.255.0") {

                                New-Object -TypeName PSCustomObject -Property @{
                                Server = $serverName
                                SubnetMask = $SubnetMask
                                
                                } | Export-Csv P:\Powershell\PSPSubnets.csv

                            Else {

                                Write-Warning "$serverName already has a /23 configuration"

                                } #Else

                    } #foreach ($ethernetAdapter in $ethernetAdapters) {

            } #If (Test-Connection -ComputerName $serverName -Quiet) {

    } #foreach ($serverName in $serverNames) {
                       
   }       
             
   

I’d say you may have been right about scripter’s block :). In your call to Get-WmiObject for the Win32_NetworkAdapterConfiguration class you’re not specifying the servername that you’re iterating through from your “ForEach($serverName in $serverNames)” loop, therefore this Get-WmiObject call will only run against your local computer, and depending on how many server names are in $serverNames it will make the call against your local computer that many times :).

Add “-ComputerName $serverName” to your Get-WmiObject call and that should sort you, assuming everything else is ok.

Export-csv needs the append parameter,

Oh my gosh. Yep, that is what happens when you work on something for several hours! Thank you.

Export-CSV command should be inside If construct.

Fantastic - I moved the export command as suggested.

Still looking for any other critiques!

Thank you,
RH

Hey mate,

to speed things up substantially ,change this line

(Test-Connection -ComputerName $serverName -Quiet) 

to

 (Test-Connection -ComputerName $serverName -Quiet -count 1) 

That will save you a ton of time. There are quite a few ways to do what you’re trying to do also. One recommendation I would make it to turn the script into an advanced function.

You may want to take a look into using invoke-command also that way you could query all your machines in your collection (from AD) at the same time rather than going though one by one.

Also, take a look at these, very helpful:
http://www.indented.co.uk/2010/01/23/powershell-subnet-math/

Here’s a quick example of what I mean, hopefully this helps:

Function Get-SubnetMask {

    [CmdletBinding()]

    Param
    (
        #Wildcards accepted
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $Computername

    )

BEGIN{
Import-Module ActiveDirectory
}
PROCESS
{
    $serverNames = Get-ADComputer -Filter "name -like '$Computername'" | Select-Object -ExpandProperty DnsHostname

      $Items = Invoke-Command $Servernames {
          
            [Net.IPAddress]$SubnetMask = (Get-WmiObject -ClassName Win32_NetworkAdapterConfiguration -Filter "ipenabled = 'true'").Ipsubnet[0] 
           if ($SubnetMask.IPAddressToString -eq "255.255.255.0")
           {
           
             "" | Select-Object @{Name='Computername';Expression={$env:COMPUTERNAME}},@{Name='Subnet Mask';Expression={$SubnetMask.IPAddressToString}}
           

           }
           else 
           {
           
           "" | Select-Object @{Name='Computername';Expression={$env:COMPUTERNAME}},@{Name='Subnet Mask';Expression={'Not a /24 mask'}}
           
           }

       } -HideComputerName 
}
END{
return $items
}   

}             

The benefit of doing it this way is that you return the single unformatted object, if you want this to return a table you can simply pipe the cmdlet to Format-Table (ft). Want it in a CSV. Pipe it to Export-CSV.

This is really great info Flynn, and thank you. I have a few questions as well.

What does the -HideComputerName tag do?

Also, I do not necessarily need to list out the subnet mask for each machine, I was only doing that as a double check to verify that the machine names I return are in fact servers that are configured as /24. So really, I could just return the computer names and that may end up being easier, as I need to have all of them reconfigured to /23. Would this make things easier on me?

Thanks again, this is very helpful! I am VERY much a n00b. :slight_smile:

Ryane

I am getting further now, but running into an error on the following line:

$ethernetAdapters = Get-WmiObject -ClassName Win32_NetworkAdapterConfiguration -Filter "ipenabled = 'true' and description like 'Intel(R) Ethernet%'" -ComputerName $serverName;       

"A parameter cannot be found that matches parameter name ‘ClassName’.

Any idea what I am doing wrong here? Thank you! :slight_smile:

Ryane

Ok - scratch the last one, I fixed that, just changed it to -Class instead of -ClassName.

However - now my script just seems to “hang” at the “Getting network information…” message and does not seem to go further. Sorry for all the updates, I’m trying to actively fix this myself at the same time as getting expert advice! :slight_smile:

Latest code, for reference:

 

[CmdletBinding()]
param (
	[Parameter(Mandatory = $true)]
	[System.String]
	$CommandLineFilePath
)

function Get-PSPSubnetMask {
	[CmdletBinding()]
	param(
		[Parameter(Mandatory=$true)]
		[System.String]
		$FilePath
	)

        Write-Verbose "Retrieving server names from text file..."

	    #Retrieve a list of PSP servers from text file and set to $serverNames
        $serverNames = Get-Content $FilePath                
    
        Write-Verbose "Gathering network information..."

        #Iterate through each of the server names
	    foreach ($serverName in $serverNames) {

			#Check if the server is online before doing the remote command
			If (Test-Connection -ComputerName $serverName -Quiet -count 1) {

                $ethernetAdapters = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "ipenabled = 'true' and description like 'Intel(R) Ethernet%'" -ComputerName $serverName;       

                    foreach ($ethernetAdapter in $ethernetAdapters) {

                        $SubnetMask  = $ethernetAdapter.IPSubnet;

                            If ($SubnetMask -eq "255.255.255.0") {

                                New-Object -TypeName PSCustomObject -Property @{
                                Server = $serverName
                                SubnetMask = $SubnetMask |
                                Export-Csv C:\Temp\PSPSubnetMask.csv -Append
                            
                                } 

                                Write-Verbose "$serverName has /24 configuration, logged"

                            Else {

                                Write-Verbose "$serverName already has a /23 configuration"

                                } #Else

                        } #foreach ($ethernetAdapter in $ethernetAdapters) {

                } #If (Test-Connection -ComputerName $serverName -Quiet) {

        } #foreach ($serverName in $serverNames) {

    } #function Get-PSPSubnetMask {
                       
   }  
   
Write-Verbose "Script completed successfully"  
             
#Run the Get-PSPSubnetMask function using the text file path that was passed to this script
Get-PSPSubnetMask -FilePath $CommandLineFilePath -Verbose
        
 

Edited your Script

Here is the final code - in case anyone was interested:

 

[CmdletBinding()]
param (
	[Parameter(Mandatory = $true)]
	[System.String]
	$CommandLineFilePath
)

function Get-PSPSubnetMask {
	[CmdletBinding()]
	param(
		[Parameter(Mandatory=$true)]
		[System.String]
		$FilePath
	)

        Write-Verbose "Retrieving server names from text file..."

	    #Retrieve a list of PSP servers from text file and set to $serverNames
        $serverNames = Get-Content $FilePath                
    
        Write-Verbose "Gathering network information..."

        #Iterate through each of the server names
	    foreach ($serverName in $serverNames) {

        Write-Verbose "Processing $serverName" 

            #Check if the server is online before doing the remote command
			If (Test-Connection -ComputerName $serverName -Quiet -count 1) {

                $ethernetAdapters = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "description like 'vmxnet3%'" -ComputerName $serverName       

                    foreach ($ethernetAdapter in $ethernetAdapters) {
     
                        $SubnetMask  = $ethernetAdapter.IPSubnet

                            If ($SubnetMask -eq "255.255.254.0") {

                                Write-Verbose "Already a /23 configuration"

                                }

                            Else {

                                New-Object -TypeName PSCustomObject -Property @{
                                Server = $serverName
                                SubnetMask = $SubnetMask } |
                                Export-Csv C:\Temp\PSPSubnetMask.csv -Append
                            
                                Write-Verbose "$serverName has non-standard configuration, logged"

                               } #Else

                    } #foreach ($ethernetAdapter in $ethernetAdapters) {

            } #If (Test-Connection -ComputerName $serverName -Quiet -count 1) {

            Else {

                $serverName | Out-File c:\temp\TPOSexceptions701.txt 
                Get-Content c:\temp\TPOSexceptions701.txt | ForEach-Object {$serverName.replace('701', '702')} | Out-File c:\temp\TPOSexceptions702.txt -Append

                }
                       
    } #foreach ($serverName in $serverNames) {  
   
} #function Get-PSPSubnetMask {

Write-Verbose "Script completed successfully"  
             
#Run the Get-PSPSubnetMask function using the text file path that was passed to this script
Get-PSPSubnetMask -FilePath $CommandLineFilePath -Verbose