powershellcomputer-name

How to check if Join a computer to a domain was succeful


I need you help... i am writing a powershell script which will add a computer to a domain. i have done this using the add-computer but my main problem is that i want to check if the join was done successful or not. If was not successful i want to try again until the action done. this is the script:

$j = add-computer -domainname mydomain -credential mydomain\
While ( $j -ne 0){
 $j = add-computer -domainname mydomain -credential mydomain\
}

If the join done or not done the script is running and it never ends.

I tried to do it with the DO... Until:

    do { 
    $j = add-computer -domainname mydomain -credential mydomain\ }
until ($j -eq o)

but i had the same problem...

Can you help me please?


Solution

  • You could specify the parameter "-PassThru" for the command "Add-Computer". Based on your input the command would look like this:

    $j = Add-Computer -DomainName mydomain -Credential mydomain\ -PassThru
    

    "$j" now contains the information, if the join was successful. You can get the status with:

    $j.HasSucceeded
    

    It will give you "$True" on success and "$False" on error. With that information you could form your IF-clause as you like:

    IF ( $j.HasSucceeded -eq $false ) { ...
    

    EDIT: A simple example based on your input:

    Do {
    
        Try {    
            $j = Add-Computer -DomainName mydomain -Credential mydomain\test -PassThru -ErrorAction Stop
        }
    
        Catch {
            $Error[0].Exception
        }
    
    } While ( $j.HasSucceeded -ne $true )
    

    Kind regards