循环问题 - 需要帮助 "refining" 我的代码

Issues with looping - Need help "refining" my code

我有自己编写的 ps 脚本。它使用关键字搜索可用的 Active Directory 组ps,如果没有找到关键字,则输出找不到任何 AD 组ps,并询问我是否要再次搜索。但是,我面临的问题是它输出找不到任何 AD groups,即使它确实找到了带有我的关键字的 groups... 这是我的代码:

$group = Read-Host "Which groups would you like to search for?"
$group = $group + "_*"
$groups = Get-ADGroup -Filter {name -like $group} -Properties * | select SAMAccountName, Description
while ($groups -eq $null) {
        if ($groups -eq $null) {
            Write-Verbose "Did not find any matching groups. Try again" -Verbose
            $group = Read-Host "Which groups would you like to search for?"
            $group = $group + "_*"
            Get-ADGroup -Filter {name -like $group} -Properties * | select SAMAccountName, Description   
    } else {
        if ($groups -ne $null) {
            Get-ADGroup -Filter {name -like $group} -Properties * | select SAMAccountName, Description  
        }
    }
}

现在,我知道这可能不是那么干净,格式可能会更好......也许吧。但是我很难理解为什么它会输出“再试一次”消息,即使结果出现了

谢谢!

如评论所述,while ($groups -eq $null) 已经测试了 'nothing found',因此您无需在循环内再次测试。

如果 Get-ADGroup cmdlet 返回任何结果,我会建议使用一个无限的 while 循环的稍微不同的方法

while ($true) {
    $group = Read-Host "Which groups would you like to search for?"
    # if the user did not enter an empty of whitespace-only string
    if (![string]::IsNullOrWhiteSpace($group)) {
        # Get-ADGroup by default already returns these properties:
        # DistinguishedName, GroupCategory, GroupScope, Name, ObjectClass, ObjectGUID, SamAccountName, SID
        # so in this case, only ask for the extra Description property
        $groups = Get-ADGroup -Filter "Name -like '$($group)_*'" -Properties Description
        if ($groups) {
            # output the two properties
            $groups | Select-Object SamAccountName, Description
            # and exit the while loop
            break
        }
    }
    # once here, you didn't find any groups on the input keyword, so let the user try again
    Write-Verbose "Did not find any matching groups. Try again" -Verbose
}

注:

  • -Filter 应该是 string 而不是 scriptblock
  • 如果您最终只关心两个属性,那么使用 -Properties * 请求 all 是非常浪费的。
  • 与 $null 的比较可以用 if($groups)if ($groups -ne $null)if(!$groups)if ($groups -eq $null) 做得更好。如果您必须与 $null 进行比较,那么最好将顺序更改为 if ($null -eq $groups)
  • 我在 "Name -like '$($group)_*'" 中使用了子表达式运算符 $(),否则 PowerShell 将尝试扩展未定义的变量 $groups_。另一种方法是使用 "Name -like '${group}_*'"