Checking if computer does not exists

This topic contains 4 replies, has 3 voices, and was last updated by  Eric Salamone 3 years, 4 months ago.

  • Author
    Posts
  • #15319

    Eric Salamone
    Participant

    We have thousands of systems and delete them after not talking to sccm's heartbeat usually, but with that sccm keeps the computer in its database for 30 days or so. So when we push a patch/program we will have computers that are not getting it, because they no longer exists. I pull the listing of computers from sccm and then run them against Get-ADComputer in a script.

    The script runs but i want the if statement to check to see if it is null else "blahh" and it does, but it sends the common error of unable to find the computer. I want it to check then go into my "if" statement not just display the error.

    if ((Get-ADComputer "$comp" ) -eq $null){....}

    Thanks for the help

  • #15321

    Daniel Krebs
    Moderator

    Hello Eric,

    A possible solution for you would be to trap the exception thrown by Get-ADComputer and remove the device from SCCM in the catch block.

    Example:

    $ComputerName = 'MyTest'
    $Domain = 'viamonstra.local'
    try
    {
    Get-ADComputer -Identity $ComputerName -Server $Domain
    }
    catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
    {
    Write-Verbose -Message ('Device "{0}" not found in Active Directory domain {1}' -f $ComputerName, $Domain)
    Write-Verbose -Message ('Removing device "{0}" from SCCM' -f $ComputerName)
    ...
    }

    Best,
    Daniel

    • #15342

      Eric Salamone
      Participant

      That looks good, I will have to look into it a lot more (just starting to learn powershell).

      Thank you for your help

  • #15322

    Richard Siddaway
    Moderator

    Try something like this

    $ErrorActionPreference = 'SilentlyContinue'
    if (-not $( Get-ADComputer -Identity "bleh")){ Write-Host "Doesn't exist"}
    $ErrorActionPreference = 'Continue'

    You can get the if statement to do whatever you need.

    The important part is remembering to reset the ErrorActionPreference variable.

    • #15341

      Eric Salamone
      Participant

      That worked perfectly. Does the variable "ErrorActionPreference" work different than the common parameter "-ErrorAction"? Thanks for the help.

You must be logged in to reply to this topic.