0

I don't know much about scripting at all, but want to help out my lead with something. I'm trying to create a script that will ask for a username and it will return when their password will expire in AD. I also want to continue inputting usernames after it has finished in case there are multiple users I need to check. Below is the script I have so far.

$User = Read-Host "Username?"
Get-ADUser $User -Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" |
Select-Object -Property "Displayname", @{Name = "ExpiryDate"; Expression = {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}

I was looking into doing loops, but I do not know how to write it out. Any help would be appreciated. Thanks.

2 Answers 2

2

You could use a do-until loop:

do {
    $User = Read-Host "Username? (enter 'q!' to quit)"
    if($User -notin @('', 'q!')){
        Get-ADUser $User -Properties DisplayName,"msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property Displayname, @{Name = "ExpiryDate"; Expression = {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}
    }
} until ($User -eq 'q!')

PowerShell will continue to repeat the code inside the do block as long as the user doesn't input q!. The if statement also prevents attempts to fetch a user when no username was provided.

Sign up to request clarification or add additional context in comments.

3 Comments

After trying and testing it out the results only show up after I type 'q!' I tried to position the loop in different parts of the script and could not seem to get it to work. Is there a way for it to show the results after each input before starting the loop again?
@adamring Sure, add | Out-Host (or | Out-Default) at the end of the Get-ADUser statement :)
Thanks so much that worked. Appreciate the help!!
0

You could also use a while loop

while ($true) {
    $User = Read-Host "Username?"
    Get-ADUser $User -Properties "DisplayName","msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "Displayname", @{Name = "ExpiryDate"; Expression = {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}
    
    if ($User -eq "q!") {
        break
        
    }
    
}

To quit the while loop enter "q!" in place of a user.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.