Powershell意外输出为$\。串

Powershell意外输出为$\。串,powershell,Powershell,当运行下面的脚本片段时 Get-ADComputer -Filter '*'| ForEach-Object { Write-output "testing $_.DnsHostName" #Do more with $_ } 我得到: testing CN=CO-ID96407D,OU=Contoso Computers,OU=Contoso Organisation,DC=contoso.DnsHostName 但我期待的是 testing CO-ID96407D.c

当运行下面的脚本片段时

Get-ADComputer  -Filter '*'| ForEach-Object { 
    Write-output "testing $_.DnsHostName"
    #Do more with $_
}
我得到:

testing CN=CO-ID96407D,OU=Contoso Computers,OU=Contoso Organisation,DC=contoso.DnsHostName
但我期待的是

testing CO-ID96407D.contoso

有人知道我在这里做错了什么吗?我只想输出
$的
DnsHostName
成员,但它似乎只是输出
AD计算机的默认输出成员。

您正在以字符串形式创建子表达式,因此必须将其包装在
$(…)
:

Write-output "testing $($_.DnsHostName)"
也可以使用格式字符串:

Write-output "testing {0}" -f $_.DnsHostName
Write-output "testing {0}" -f $_.DnsHostName