Search code examples
powershellselectreplacepowershell-3.0

Replace part of Select Statement in Powershell


I'm working with Powershell to get some information out of DHCP server. I'm using this command to get the information i need.

Get-DhcpServerv4Lease -ScopeId 10.132.56.0 | select IPAddress,ClientId,HostName | sort hostname | format-table

Results are as i expect:

| IPAddress | ClientId | HostName | |---------------|-------------------|-----------| | 10.132.56.121 | 40-83-de-2b-66-27 | | | 10.132.56.101 | 40-83-de-2b-64-fb | | | 10.132.56.76 | 4c-c9-5e-6d-f2-30 | [Signage] |

I wih to remove the "-" from the ClientId.

I've tried the -replace "*","" I've tried

Get-DhcpServerv4Lease -ScopeId 10.132.56.0 | select IPAddress,$_.ClientId -replace "-","" ,HostName | sort hostname | format-table
*Select-Object : A parameter cannot be found that matches parameter name 'replace'.
At line:1 char:75
+ Get-DhcpServerv4Lease -ScopeId 10.132.56.0 | select IPAddress,$_.ClientId -repla ...
+                                                                           ~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-Object], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SelectObjectCommand$_.ChildID.replace("-","")*

But i get different errors.

I wish i can do it on one line without storing variables of arrays.

Any help? Maybe it's impossible, but i doubt it.


Solution

  • You need to enclose the -replace operation in a property expression:

    ... Select IPAddress,{$_.ClientId -replace '-'},...
    

    If you want the resulting property to retain the name ClientId, wrap the property expression in a hashtable (this is sometimes referred to as a calculated property):

    ... Select IPAddress,@{Name='ClientId';Expression={$_.ClientId -replace '-'}},...