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

时间:2020-07-01 12:53:19

标签: powershell active-directory powershell-4.0

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

$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

1 个答案:

答案 0 :(得分:2)

-Property的{​​{1}}参数需要单个属性或属性数组。由于Select-Object已经是数组,因此您需要使用$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不会将其作为单个阵列展开。