user10205566
user10205566

Reputation:

Powershell-else in try/catch

I'm trying to write output when get-addomain succeded.

Try/catch writes output only if command fails

try {

get-addomain -Identity  d.contoso.com  

}

catch {

Write-Output "failed"

}

I tried following:

if (-not (get-addomain -Identity  d.contoso.com))
{
return "failed"
}

else

{
write-output "ok"
}

and

If (get-addomain -Identity  d.contoso.com  )
{
    Write-Output "ok"
}
Else
{
    write-output "failed"
}

but in both cases got

get-addomain : Cannot find an object with identity: 'd.contoso.com' under: 'DC=ad,DC=contoso,DC=com'.

Upvotes: 0

Views: 5290

Answers (2)

Bernard Moeskops
Bernard Moeskops

Reputation: 1283

try{
    $domain = Get-ADDomain -Identity d.contoso.com
    Write-Output $domain
}catch{
    Write-Output "Failed with message '$($_.Exception.Message)'"
}

When you use the AD CmdLets, it fails when a non-existing identity is specified. Therefore if the object you search for does not exist, you will end up in the catch. The first piece of code you wrote is actually correct if you wish to output the AD domain information.

Upvotes: 0

Paxz
Paxz

Reputation: 3036

The tryblock runs until a error is getting thrown. If get-addomain doesn't end with an error, the try-case will run the following commands written inside the {}.

So one way would be to just say the output is ok if no error gets thrown:

try {
  get-addomain -Identity  d.contoso.com  
  Write-Output "ok"
}

catch {
  Write-Output "failed"
}

But if you want to double check, you can still do the if check in the try-catch:

try {
  If (get-addomain -Identity  d.contoso.com  )
  {
      Write-Output "ok"
  }
  Else
  {
    write-output "failed"
  }
}
catch {
  Write-Output "failed"
}

Upvotes: 3

Related Questions