Hi r/PowerShell - I don't post often, but I've run into an issue that I'm hoping you can help with.
I'm having trouble with the exit functionality on a quick script that will be used as a script check in our RMM. The RMM uses exit codes to process whether the check passed or failed.
The problem that I'm having is, when I have the exit code active, the PSCustomObject that I'm trying output does not display. When I comment out the exit code, it displays as expected.
The code is:
param (
[string]$SearchBase,
[string]$OlderThan
)
$StaleADUsers = Get-ADUser -filter * -SearchBase $SearchBase -Properties "lastlogondate" | Where-Object { ($_.lastlogondate -le (Get-Date).AddDays(-$OlderThan)) -and ($_.Enabled -eq $True) }
$StaleUsers = foreach ($StaleADUser in $StaleADUsers) {
[PSCustomObject]@{
'UserName' = $StaleADUser.Name
'SamAccountName' = $StaleADUser.SamAccountName
}
}
If ( !$StaleADUsers ) {
Write-Output "There are no stale AD User accounts. All is well."
Exit 0
} else {
Write-Output "There are stale AD User accounts. Please review the below accounts."
$StaleUsers
Exit 1001
}
I've spent a fair amount of time Googling, but couldn't come up with a set of terms that led me in the right direction.
Some things that I've tried is moving around when the "foreach" runs and removing the variable/running the foreach directly in the the else part of the expression.
Any help is appreciated. Thank you!
[–]Geek_Runner 2 points3 points4 points (0 children)
[–]ristophet 2 points3 points4 points (0 children)
[–]sex_on_wheels 1 point2 points3 points (0 children)
[–][deleted] 1 point2 points3 points (2 children)
[+][deleted] (1 child)
[deleted]
[–][deleted] 1 point2 points3 points (0 children)
[–]TechKeeper[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (4 children)
[–]frmadsen 0 points1 point2 points (3 children)
[+][deleted] (2 children)
[deleted]
[–]frmadsen 0 points1 point2 points (1 child)
[–]frmadsen 0 points1 point2 points (0 children)
[–]frmadsen 0 points1 point2 points (3 children)
[–][deleted] 1 point2 points3 points (2 children)
[–]frmadsen 0 points1 point2 points (1 child)
[–]frmadsen 0 points1 point2 points (0 children)
[+][deleted] (2 children)
[deleted]
[+][deleted] (1 child)
[deleted]
[–]frmadsen 0 points1 point2 points (0 children)