I want to take a couple commands and bring them together, but am unsure of how to do this.
I want to grab all the groups in a specific OU - This works to grab all the groups in the specified OU
$Grouplist = Get-ADGroup -Filter * -SearchBase "OU=*ou name*, OU=*ou name*, OU=*ou-name*, DC=*domain*, DC=local | Sort-Object | Select Name
Then I want to search through those groups and grab all the members in those group and grab their lastlogontimestamp and list any outside of the last 90 days - This works when I use a specific group name
Get-ADGroupMember **$GROUPLIST VARIABLE?** -Recursive | Get-ADObject -Properties Name, DisplayName, samAccountName, LastLogonTimestamp | Select-Object Name, DisplayName, samAccountName, @{ n = "LastLogonTimeDate"; e = { [System.DateTime]::FromFileTime($_.LastLogonTimeStamp) } }
I know I need to use a ForEach for this, but I don't know how - I believe this is where I should go?
ForEach ($Group in $Grouplist) ??
I know I am missing some key elements, but I am having a hard time finding what I am missing and even if I did, I am not sure I can bring it all together. The end result I am looking for is a loop that goes through each group it finds in the specified OU, grabs all the members of those groups along with their last logon and then filters to show only the users whose last logon is 90 days or greater.
I found a function somebody wrote going, I believe, in the same direction I am
function Get_LogonTimes { [CmdletBinding()] param ( [parameter(Position=0, Mandatory=$true)] $Groups ) $table = @() foreach($group in $Groups) { $users = (Get-ADGroup -Identity $group | Get-ADGroupMember |Where-Object {$_.objectClass -eq "user"}).SamAccountName foreach($user in $users) { $acct = Get-ADUser -Identity $user -Properties * $table += New-Object -TypeName psobject -Property @{ Name = $acct.Name UserName = $acct.SamAccountName LastLogon = $acct.LastLogonDate Group = $group } } } $logontimes = $table | Select Name,UserName,LastLogon,Group return $logontimes }
Like so many, I am still in the learning stages of PowerShell. Any help is appreciated, thank you!