0

The below code keeps getting stuck in a loop when it gets to

$choice = read-host "Are you sure you want to disable the following user? (Y/N)" "$name"

I type in y and it keeps looping that question.

I've tried a do while & single IF statement. Any ideas on how to stop this loop?

$choice = ""
$User = read-host "enter username"
$Name = Get-ADuser -Identity $Username | Select-Object Name

while ($choice -notmatch "y/n"){
    $choice = read-host "Are you sure you want to disable the following user? (Y/N)" "$name"

    If ($Choice -eq"Y"){
        Disable-ADAccount $Username
    } 
}

1 Answer 1

7

You need to use the pipe for an or statement to work not a slash

This...

while ($choice -notmatch "y/n"

...should be this...

while ($choice -notmatch "y|n"

This is wrong, because you do not have a populated variable in the posted code to use...

Disable-ADAccount $Username

... based on your code, it should be this...

Disable-ADAccount $User

No need to seperate the variable in the choice statment. Just do this.

$choice = read-host "Are you sure you want to disable the following user? (Y or N) $name"

Example:

$choice = ""
$User = read-host "enter username"
$Name = $User

while ($choice -notmatch "y|n")
{
    $choice = read-host "Are you sure you want to disable the following user? (Y/N) $Name"

    If ($Choice -eq "y")
    { $User } 
}

enter username: test
Are you sure you want to disable the following user? (Y/N) test: u
Are you sure you want to disable the following user? (Y/N) test: u
Are you sure you want to disable the following user? (Y/N) test: y
test


enter username: test1
Are you sure you want to disable the following user? (Y/N) test1: h
Are you sure you want to disable the following user? (Y/N) test1: h
Are you sure you want to disable the following user? (Y/N) test1: n
Sign up to request clarification or add additional context in comments.

1 Comment

My two pennies: while ($choice -notin "y", "n") {... is simpler and easier to understand

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.