23

所以我正在调整一些 Powershell 库,我有一个简单的问题,我想以最好的方式解决......

简而言之,我在数组中有一些自定义 PSObject:

$m1 = New-Object PSObject –Property @{Option="1"; Title="m1"}
$m2 = New-Object PSObject –Property @{Option="2"; Title="m2"}
$m3 = New-Object PSObject –Property @{Option="3"; Title="m3"}

$ms = $m1,$m2,$m3

我希望将其转换为字符串数组....理想情况下是单个字符串数组,其中每个项目都有一个连接属性的条目。IE

“1m1”、“2m2”、“3m3”

我试过了$ms | Select-Object Option,Title$ms | %{ "O: $_.Option T: $_.Title "} 但他们给了我 PSObject 的数组(再次)或数组的数组。

4

2 回答 2

46

这会给你你想要的:

$strArray = $ms | Foreach {"$($_.Option)$($_.Title)"}

Select-Object有点像 SQL SELECT。它将选定的属性投影到一个新对象上(v1/v2 中的 pscustomobject 和 V3 中的 Selected.<orignalTypeName>)。您的第二种方法不起作用,因为$_.Option在字符串中只会“插入”变量$_。它不会评估表达式$_.Option

您可以通过使用子表达式获取双引号字符串来评估表达式,例如“$(...)”或“$($_.Option)”。

于 2013-01-15T16:09:08.877 回答
0

doesn't contain a method named 'op_Addition'.尝试收集对象值并将它们添加到数组集合时,我也收到了相同的错误消息。@(用and包裹变量时效果很好)

这是一篇参考文章:

PS脚本数组集合

##USER PROFILES...
$UserProfiles= @("cg2208", "cg0769", "ms8659", "sw1650", "dc8141", "bc0397", "bm7261")
$UserProfiles
$aduserlist = @()
foreach ($user in $UserProfiles {
  $user 
  #Write-Host "Press any key to continue ..."
  #$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$aduser= Get-ADUser -Identity $user -Properties * | Select -Property  SamAccountName, Name, LastLogonDate, whenCreated, msExchWhenMailboxCreated, City, State, Department, Title, mailNickname, Description
#$aduserlist += $aduser | Select Name, SamAccountName, City, State, Department, Title, whenCreated, msExchWhenMailboxCreated, mailNickname, Description
#$aduserlist += $aduser | Foreach {"$($_.SamAccountName)$($_.Name)$($_.City)$($_.State)$($_.Title)$($_.whenCreated)$($_.msExchWhenMailboxCreated)$($_.mailNickname)$($_.Description)"}
$aduserlist += @($aduser)  
}
$aduserlist
$aduserlist | ft -auto 
于 2020-02-11T22:44:21.343 回答