Sort in Get-ADComputer

As per my comments, there is quite a few things wrong with your code.

You are defining a regex, where it really is a wildcard string. Later on you compare IP addresses to this “regex” with the assignment operator =

By using | FT CN,IPv4Address, your variable $scan will contain a string array, not an array of objects you need for creating a valid CSV file

Try

$ipRange = "192.168.0.*"
$refDate = (Get-Date).AddDays(-30).Date  # set time part to all 0, so this date is midnight
$scan = Get-ADComputer -Filter * -Properties CN,LastLogonDate,IPv4Address |
        Where {$_.LastLogonDate -ge $refDate -and $_.IPv4Address -like $ipRange} | 
        Sort-Object -Property @{Expression = {[int]($_.IPv4Address.Split(".")[-1])}}

# output to console
$scan | Format-Table -AutoSize

# output to CSV
$scan | Export-Csv -Path 'C:\comps192.168.csv' -NoTypeInformation

The line Sort-Object -Property @{Expression = {[int]($_.IPv4Address.Split(".")[-1])}} uses a calculated property to sort on. In this case the integer value of the last IP addresses octet. That way, IP 192.186.0.2 will be sorted before 192.168.0.11, whereas if you sort on the ip strings the result would be the other way around.
Also, with Get-ADComputer, you can ask for property LastLogonDate, which is the value of lastLogonTimeStamp already converted to a (local) DateTime object.


Edit

If, as you commented, your aim is to test if the IP address is inside a certain subnet, you could make use of below helper function

function Test-IsIPv4InSubnet ([string]$IpAndCidr, [string]$IpAddress) {
    $network, [int]$subnetlen = $IpAndCidr.Split('/')
    $a = [uint32[]]$network.split('.')
    [uint32] $unetwork = ($a[0] -shl 24) + ($a[1] -shl 16) + ($a[2] -shl 8) + $a[3]

    $subnetlen = [Math]::Min([Math]::Max([Math]::Abs($subnetlen), 0), 32)
    $mask = (-bnot [uint32]0) -shl (32 - $subnetlen)

    $a = [uint32[]]$IpAddress.split('.')
    [uint32] $uip = ($a[0] -shl 24) + ($a[1] -shl 16) + ($a[2] -shl 8) + $a[3]

    return ($unetwork -eq ($mask -band $uip))
}

With that in place on top of your script, the code can be like:

$ipSubnet = "192.168.0.0/24"
$refDate = (Get-Date).AddDays(-30).Date  # set time part to all 0, so this date is midnight
$scan = Get-ADComputer -Filter * -Properties CN,LastLogonDate,IPv4Address |
        Where {$_.LastLogonDate -ge $refDate -and (Test-IsIPv4InSubnet $ipSubnet $_.IPv4Address)} | 
        Sort-Object -Property @{Expression = {[int]($_.IPv4Address.Split(".")[-1])}}

# output to console
$scan | Format-Table -AutoSize

# output to CSV
$scan | Export-Csv -Path 'C:\comps192.168.csv' -NoTypeInformation

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top