Powershell Get-ADUser 已计算 属性 Select-对象:无法转换 System.String[]?

Powershell Get-ADUser calculated property Select-Object : Cannot convert System.String[]?

下面这个工作正常,没有问题:

$properties = 'Name,msExchRemoteRecipientType,msExchRecipientDisplayType,msExchRecipientTypeDetails,proxyAddresses' -split ','
Get-ADUser -identity 'Lee.Xia' -Properties $properties |
Select-Object $properties

但是下面这个格式的电子邮件地址只用 SMTP 不起作用? 添加此行:@{Label = 'Email Address'; Expression = {($_.proxyAddresses | Where-Object {($_ -like 'SMTP*') -and ($_ -notlike '*onmicrosoft.com') } | Sort-Object -CaseSensitive -Descending | ForEach-Object {$_.Split(':')[1]}) -join ', ' }}

所以它会像:

$properties = 'Name,msExchRemoteRecipientType,msExchRecipientDisplayType,msExchRecipientTypeDetails,proxyAddresses' -split ','
Get-ADUser -identity 'Lee.Xia' -Properties $properties |
Select-Object $properties, @{Label = 'Email Address'; Expression = {($_.proxyAddresses | Where-Object {($_ -like 'SMTP*') -and ($_ -notlike '*onmicrosoft.com') } | Sort-Object -CaseSensitive -Descending | ForEach-Object {$_.Split(':')[1]}) -join ', ' }}

这是错误代码:

Select-Object : Cannot convert System.String[] to one of the following types {System.String, System.Management.Automation.ScriptBlock}.
At line:3 char:1
+ Select-Object $properties, @{Label = 'Email Address'; Expression = {( ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Select-Object], NotSupportedException
    + FullyQualifiedErrorId : DictionaryKeyUnknownType,Microsoft.PowerShell.Commands.SelectObjectCommand

Select-Object-Property 参数需要单个 属性 或属性数组。由于 $properties 已经是一个数组,您需要使用 + 而不是 ,.

将计算出的 属性 添加到其中
$properties = 'Name,msExchRemoteRecipientType,msExchRecipientDisplayType,msExchRecipientTypeDetails,proxyAddresses' -split ','
Get-ADUser -identity 'Lee.Xia' -Properties $properties |
Select-Object ($properties + @{Label = 'Email Address'; Expression = {($_.proxyAddresses | Where-Object {($_ -like 'SMTP*') -and ($_ -notlike '*onmicrosoft.com') } | Sort-Object -CaseSensitive -Descending | ForEach-Object {$_.Split(':')[1]}) -join ', ' }})

使用 , 而不是 + 创建一个包含两个元素的数组。第一个元素是 $properties 的数组。第二个元素是计算出来的属性。 Select-Object 不会将其展开为单个数组。