Johny Corbie
Johny Corbie

Reputation: 63

Powershell $? in do until loop

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?

Upvotes: 1

Views: 1010

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

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) {

Upvotes: 3

Related Questions