1

I'm trying to make a loop for joining a Windows domain in PowerShell with usage of $?, which should return false/true if last command returned error or not.

This is what I got:

Add-Computer -DomainName "domainname.local" -Credential "admin"

$MaxAttempts = 0
do {
    if ($? -like "false" -and $MaxAttempts -lt 5) {
        $MaxAttempts += 1
        Write-Host "Attempt" $MaxAttempts "out of 5"
        Add-Computer -DomainName "domainname.local" -Credential "admin"
    } else {
        Write-Host "test"
    }

Problem is when I have first command outside of that do/until loop it's returning true even when I get an error. But when I add this command to do/until loop it returns false as expected but that way im running that command twice and that's not I want.

Can someone explain me this sorcery?

1 Answer 1

3

The automatic variable $? contains true or false depending on whether or not the previous PowerShell statement completed successfully. The last PowerShell statement before you check the value of $? inside the loop is $MaxAttempts = 0, which changes the value of $? to true (because the assignment operation succeeded), even if the Add-Computer statement before that failed.

I'd recommend adjusting your loop to something like this:

$MaxAttempts = 0
do {
    Add-Computer -DomainName "domainname.local" -Credential "admin"
    $success = $?
    if (-not $success) {
        $MaxAttempts++
    }
} until ($success -or $MaxAttempts -ge 5) {
Sign up to request clarification or add additional context in comments.

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.