0
votes

Basicly i want to find inactive users so im using a foreach loop in a search base,

Now im trying to impliment looking at several OU's winthin an array at the start.

So this is what i was trying...

$OU=@("OU Path 1",
        "OU Path 2",
        "OU Path 3")

$OU | ForEach ($user in (Get-ADUser -SearchBase $_ -filter {(lastlogondate -notlike "*" -OR lastlogondate -le $90days) -AND (passwordlastset -le $90days) -AND (enabled -eq $True)} -Properties lastlogondate, passwordlastset | Select-Object name, lastlogondate, passwordlastset, samaccountname))
{

....

and getting the error....

At line:18 char:22 + $OU | ForEach ($user in (Get-ADUser -SearchBase $_ -filter {(lastlogondate -notl ... + ~~ Unexpected token 'in' in expression or statement. At line:18 char:21 + $OU | ForEach ($user in (Get-ADUser -SearchBase $_ -filter {(lastlogondate -notl ... + ~ Missing closing ')' in expression. At line:18 char:293 + ... samaccountname)) + ~ Unexpected token ')' in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken

This Works Fine

$SearchBase1 = "OU1"
$SearchBase2 = "OU2"
$SearchBase3 = "OU3"


ForEach ($user in(Get-ADUser -SearchBase $SearchBase1 -filter {(lastlogondate -notlike "*" -OR lastlogondate -le $90days) -AND (passwordlastset -le $90days) -AND (enabled -eq $True)} -Properties lastlogondate, passwordlastset | Select-Object name, lastlogondate, passwordlastset, samaccountname))
{
1

1 Answers

1
votes

The problem is that you are trying to created a nested ForEach loop, and forgot the first part of the loop. Here, you want to pipe $OU into a ForEach loop, and within that ForEach loop create another loop based on the current object of the first ForEach loop.

$OU | ForEach{
    ForEach ($user in (Get-ADUser -SearchBase $_ -filter {(lastlogondate -notlike "*" -OR lastlogondate -le $90days) -AND (passwordlastset -le $90days) -AND (enabled -eq $True)} -Properties lastlogondate, passwordlastset | Select-Object name, lastlogondate, passwordlastset, samaccountname))
    {
        <Do Stuff>
    } #End inner ForEach Loop for current OU
}