为什么foreach列表中运行为$i的第一个项目最终为空或与列表中的下一个项目混在一起



基本上,这只是使用powershell来查询组的成员并对结果进行排序。如果我一次执行一个命令,它会很好,但当我将其添加到脚本中时,第一个条目会变成空白,或者将一些第一个用户与foreach的第二个条目混合。。。

import-module activedirectory
$share = get=content "list.txt"
foreach ($i in $share){
get-adgroupmember $i | sort | select-object samaccountname,name
}

我猜您需要一个组中所有用户对象的报告(Get-ADGroupMember可以返回用户、计算机或组(,并希望在结果中显示这些用户的SamAccountName和Name属性。

由于您的代码不会返回共享本身的名称,因此无法判断哪些用户是哪个组的成员,因此这将解释您所说的"将一些第一用户与foreach"的第二条目混合

此外,正如所评论的,文本文件中的(一些(项目周围可能有空行或前导/尾随空格。

尝试:

# read the group names from the file. 
# skip empty lines and make sure the names are not surrounded by whitespace
$groups = (Get-Content -Path "list.txt" | Where-Object { $_ -match 'S' }).Trim()
$result = foreach ($group in $groups) { 
Get-ADGroupMember -Identity $group -Recursive | 
Where-Object {$_.objectClass -eq 'user'} |
Select-Object @{Name = 'Group'; Expression = {$group}}, SamAccountName, Name |
Sort-Object Name
}
# output on screen
$result | Format-List
# output to csv file
$result | Export-Csv -Path 'D:TestGroups.csv' -NoTypeInformation

至于输出,您希望它的格式不同。一旦对象存储在$result变量中,您就可以随心所欲地发挥创意。

类似于:

# group the results by the Group (share) property
# and output the usernames beneath that group name
$result | Group-Object Group | Sort-Object Name | ForEach-Object {
# output the group (share) name with a dash line beneath it
"{0}`r`n{1}" -f $_.Name, ('-' * $_.Name.Length)
# next output the usernames
foreach ($user in $_.Group) {
'{0}, {1}' -f $user.SamAccountName, $user.Name
}
# output an empty divider line
''
}

当然,您也可以捕获此输出并稍后显示,或者保存为文本文件

$final = $result | Group-Object Group | Sort-Object Name | ForEach-Object { .. }
# show on screen
$final
# save as file
$final | Set-Content -Path 'D:TestGroupsFinal.txt'

输出看起来像

ShareGroup1
-----------
jdoe, John Doe
hbloggs, Henry Bloggs
ShareGroup2
-----------
ppicasso, Pablo Picasso

最新更新