Powershell脚本获取包含特定名称的所有组

Powershell Script to get all groups containing specific name

好的,所以我对 powershell 有点陌生,我正在尽我所能,但似乎无法做到这一点。

我的目录设置方式是每个组织都有自己的 "Password Reset Group" 我将设置一个基于事件日志条目运行的计划任务 "Directory Service Change"。该脚本的工作是查找组中的成员并将他们的密码重置回他们的 employeeNumber,让用户在下次登录时更改密码,然后从组中删除该用户。我似乎无法正确使用语法。

Try {
$GroupDN = (Get-ADGroup -Filter {Name -like '*Password Reset Group*'}).DistinguishedName
}

Catch {
    Write-Host "Unable to locate group: $Group because ""$($Error[0])""" -ForegroundColor Red
    Exit
}
ForEach ($User in (Get-ADUser -Filter * -Properties MemberOf,employeeNumber))
{   If ($User.MemberOf -contains $GroupDN)
    {   $password = "$($_.employeeNumber)new!" | ConvertTo-SecureString -AsPlainText -Force
        Set-ADAccountPassword -Identity $User -NewPassword $password -Reset
        Remove-ADGroupMember -Identity "$GroupDN" -Members $User

        }
        }

使用@AdminOfThings 给我的信息。我能够编写我想要的代码。花了很多时间,但这里是:

ForEach ($GroupDN in (Get-ADGroup -Filter {Name -like '*Password Reset Group*'}).DistinguishedName)
    { ForEach ($User in (Get-ADUser -Filter * -Properties MemberOf,employeeNumber))
{   If ($User.MemberOf -contains $GroupDN)
    {   $password = $User.employeeNumber | ConvertTo-SecureString -AsPlainText -Force
        Set-ADAccountPassword -Identity $User -NewPassword $password -Reset
        Set-ADUser -Identity $User -ChangePasswordAtLogon $true -PasswordNeverExpires $false
        Remove-ADGroupMember -Identity "$GroupDN" -Members $User -Confirm:$false

        }
        }
        }

很高兴看到您提出了自己的答案,但您可以通过使用 ...

来简化它

Get-ADPrincipalGroupMembership

# get function / cmdlet details
(Get-Command -Name Get-ADPrincipalGroupMembership ).Parameters
Get-help -Name Get-ADPrincipalGroupMembership  -Full
Get-help -Name Get-ADPrincipalGroupMembership  -Online
Get-help -Name Get-ADPrincipalGroupMembership  -Examples

# Example 2: Get group memberships for the Administrator

Get-ADPrincipalGroupMembership -Identity Administrator

... 列出用户所属的所有组。

所以,你的调整可能就是这样......

Get-ADUser -Filter * | 
ForEach{ 
    # "`n--- Processing user $($PSItem.SamAccountName) ---`n"
    If ($TargetGroup = (Get-ADPrincipalGroupMembership -Identity $PSItem.SamAccountName) -match 'Password Reset Group')
    {
        $password = "$($PSItem.employeeNumber)new!" | 
        ConvertTo-SecureString -AsPlainText -Force

        Set-ADAccountPassword -Identity $PSItem.SamAccountName -NewPassword $password -Reset
        Remove-ADGroupMember -Identity $TargetGroup.SamAccountName -Members $PSItem.SameAccountName
    }
}

至于……

Okay, so I am a little new to powershell

…这很好,但谨慎的做法是花时间熟悉 PowerShell 以限制/避免猜测、误解、沮丧、坏习惯、错误等,你将要去继续遇到(即使是我们中最有经验的人也会这样做并从中学习)。我们有大量免费/免费资源供您利用。

YouTube, MVA, MSDN Channel9 直播所有视频培训。 使用将为您编写代码的工具,您可以在以后根据需要保存和调整这些代码。特别是涉及到 ADDS 时。

Active Directory Administrative Center: Getting Started

Active Directory Administrative Center

Step-By-Step: Utilizing PowerShell History Viewer in Windows Server 2012 R2

免费Books and references