Search code examples
powershellwindows-serverdhcp

DHCP Powershell sort


Ok, so this is more of a basic Powershell question I'm pretty sure, but here's what I am trying to do:

I am writing a quick script that reads all DHCP leases on a given scope, finds any matches for client names (in this case with 'iphone' in the name), then removes those leases from DHCP. Here's what I have so far:

$leases = Get-DhcpServerv4Lease -ScopeId 192.168.1.0 | select hostname, clientid
#Find all hostnames w/ 'android' or 'iphone' in name, delete lease
$trouble = $leases | select-string -Pattern "android","iphone","ipad"
Remove-DhcpServerv4Lease -ScopeId 192.168.1.0 -ClientId $trouble

The issue is that the output of $trouble now looks like this:

@{hostname=Someones-iPhone.domain.com; clientid=00-00-00-00-c7-cc}

Since I can't remove a lease based on host name (since that isn't globally unique, I assume), I need to pass the MAC, aka client ID.

How can I get the output to slim down to just have the clientid, without all the other data? I've googled my heart out, and it's not helping. Thanks in advance!


Solution

  • You don't need to use Select-String in order to filter by a property name - use Where-Object:

    $Troubles = Get-DhcpServerv4Lease -ScopeId 192.168.1.0 | Where-Object {
        $_.Hostname -match "android" -or
        $_.Hostname -match "iphone"  -or 
        $_.Hostname -match "ipad"
    } | Select-Object ClientId
    

    If you just want the value of ClientId, use Select-Object -ExpandProperty ClientId