在 Powershell 中替换部分 Select 语句

时间:2021-02-17 15:53:48

标签: powershell select replace powershell-3.0

我正在使用 Powershell 从 DHCP 服务器获取一些信息。 我正在使用这个命令来获取我需要的信息。

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

结果如我所料:

<块引用>

| IP地址 |客户 ID |主机名 | |---------------|-------------------|-----------| | 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 | [标牌]|

我想从 ClientId 中删除“-”。

我试过 -replace "*","" 我试过了

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("-","")*

但我得到了不同的错误。

我希望我可以在一行上完成而不存储数组变量。

有什么帮助吗? 也许这是不可能的,但我对此表示怀疑。

1 个答案:

答案 0 :(得分:2)

您需要将 -replace 操作括在一个属性表达式中:

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

如果您希望结果属性保留名称 ClientId,请将属性表达式包装在哈希表中(有时称为计算属性):

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