首页 > 解决方案 > 在 Powershell 中替换部分 Select 语句

问题描述

我正在使用 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("-","")*

但我得到不同的错误。

我希望我可以在不存储数组变量的情况下在一行上完成。

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

标签: powershellselectreplacepowershell-3.0

解决方案


您需要将-replace操作包含在属性表达式中:

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

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

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

推荐阅读