我必须在PowerShell中创建一个脚本,以显示用户所属的所有组。此外,如果开关-ListAllMembers
处于打开状态,它还应显示这些组的所有成员。关键是我的脚本将不同组的所有成员显示为一个对象(数组),而我希望将它们划分。 Get-LocalGroupMember
命令处于foreach
循环中。我该怎么办?
Param(
$userToCheck,
[switch]$listAllMembers
)
function CheckIfBelongs {
foreach ($user in Get-LocalGroupMember $args[0]) {
if ($user.Name -eq ($env:USERDOMAIN + "\" + $args[1])) {
return $true
}
}
return $false
}
if (!$userToCheck) {
$userToCheck = $env:USERNAME
}
Write-Host "`nUser $userToCheck belongs to these local groups:`n"
foreach ($group in Get-LocalGroup) {
if (CheckIfBelongs $group $userToCheck) {
Write-Host $group.Name
if ($listAllMembers) {
Get-LocalGroupMember $group
}
}
}
exit 0
答案 0 :(得分:0)
Write-Host
直接写入主机控制台。默认输出(由Get-LocalGroupMember
产生)输出到success output stream。不能保证跨流的输出顺序。此外,在输出与表相同类型的对象时,PowerShell默认格式会抑制其他表头。因此,您只能看到一个表,并且主机输出在该表之前。
将Write-Host
更改为Write-Output
,输出将达到您的期望。
答案 1 :(得分:0)
Finally, I managed to solve the issue. I used Out-String
to convert the object to a string and then to send it to the console. Now, it works perfectly.