假设我有一个csv文件,如下所示:
role member
role1 memberA
role1 memberB
role2 memberC
role3 memberX
role3 memberY
role3 memberC
我想将数据库中角色的所有成员添加到数据库中
$csvR = (Import-Csv $csvFile).role
foreach ($Role in $csvR)
{
foreach ($Member in $Role)
{
& ".\AddMembers.ps1" -AddtoDatabaseOnOneServer "$Role" "$Member" "$DatabaseName" "$ServerInput"
}
}
此循环是否可以识别例如将memberA添加到role1,将memberB添加到role1,将memberC添加到role2,等等?换句话说,此内循环是否正确:foreach ($Member in $Role)
答案 0 :(得分:1)
这是一个演示如何使用Group-Object
cmdlet通过分组属性遍历导入的CSV文件中的项目的演示。 [咧嘴]
在give person
行中,您可以将呼叫添加到每个人的脚本中,也可以收集该.Role
的所有人的姓名并将其全部添加。
# fake reading in a CSV file
# in real life, use Import-CSV
$InStuff = @'
role, member
role1, memberA
role1, memberB
role2, memberC
role3, memberX
role3, memberY
role3, memberC
'@ | ConvertFrom-Csv
$GroupedIS = $InStuff |
Group-Object -Property Role
foreach ($GIS_Item in $GroupedIS)
{
foreach ($GG_Item in $GIS_Item.Group)
{
'give person [ {0} ] the role [ {1} ]' -f $GG_Item.Member, $GG_Item.Role
}
}
输出...
give person [ memberA ] the role [ role1 ]
give person [ memberB ] the role [ role1 ]
give person [ memberC ] the role [ role2 ]
give person [ memberX ] the role [ role3 ]
give person [ memberY ] the role [ role3 ]
give person [ memberC ] the role [ role3 ]