powershell 执行foreach和if语句中的第一个命令一次

svmlkihl  于 2023-01-05  发布在  Shell
关注(0)|答案(2)|浏览(141)

我想运行foreach和if语句中的第一个命令一次,并保持第二个命令运行。
输出应该是这样的。

Group-1
User-1 is added in more than one group
User-7 is added in more than one group

Group-2
User-3 is added in more than one group

Group-3
User-12 is added in more than one group
User-0 is added in more than one group

我试了很多东西,但我只得到了这一件

Group-1
User-1 is added in more than one group
Group-1
User-7 is added in more than one group
Group-2
User-3 is added in more than one group
Group-3
User-12 is added in more than one group
Group-3
User-0 is added in more than one group

谢谢你的支持。
我的代码:

$aadgroupsstrings = '9a8f8f','9a739s0','8g838a'

Foreach ($group in $aadgroupsstrings) { 

$users = Get-AzureADGroupMember -ObjectId $group -All $true
$aadgroupDisplayName = get-azureadgroup -ObjectId $aadgroups | select  -ExpandProperty DisplayName

Foreach ($user in $users) {
$groups = $user | Get-AzureADUserMembership -All $true


if (($groups.DisplayName -like "Group*").count -gt 1)  { 
    Write-Host $aadgroupDisplayName -ForegroundColor Green
    Write-Host $user.DisplayName "is added in more than one group." -ForegroundColor Yellow
    }
 }
    
    }
vecaoik1

vecaoik11#

一个计数器,用于在servername的write-host之前使用if-语句的用户,以确保servername仅显示在第一个用户名之前:

$counter=0
Foreach ($user in $users) {
$groups = $user | Get-AzureADUserMembership -All $true

if (($groups.DisplayName -like "Group*").count -gt 1)  { 
    if($counter -eq 0){
        Write-Host $aadgroupDisplayName -ForegroundColor Green
    }
    Write-Host $user.DisplayName "is added in more than one group." -ForegroundColor Yellow
    }
    $counter++

 }
    
    }
flvlnr44

flvlnr442#

我认为这可能只是你的write-host语句在错误的位置上的一个例子。给予这个改变。

$aadgroupsstrings = '9a8f8f','9a739s0','8g838a'

Foreach ($group in $aadgroupsstrings) { 

    $users = Get-AzureADGroupMember -ObjectId $group -All $true
    $aadgroupDisplayName = get-azureadgroup -ObjectId $aadgroups | select  -ExpandProperty DisplayName
    Write-Host $aadgroupDisplayName -ForegroundColor Green

    Foreach ($user in $users) {
        $groups = $user | Get-AzureADUserMembership -All $true

        if (($groups.DisplayName -like "Group*").count -gt 1)  {     
            Write-Host $user.DisplayName "is added in more than one group." -ForegroundColor Yellow
        }
    }
    
}

相关问题