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?