Share via

improve powershell function

matteu31 512 Reputation points
2021-01-05T08:18:09.783+00:00

Hello,

I write some function to audit Active directory and I think I don't use them "correcctly".
I write a sample here :

#Function to check if LAPS is installed on Active Directory to manage local administrator password.
#If attribute exists, schema is extended -> LAPS is used.
#If attribute doesn't exist, schema is not extended. -> LAPS is not used.
function Get-LAPSExists {
    try{
        get-ADObject "CN=ms-mcs-admpwd,$((get-adrootDSE).schemaNamingContext)" | Out-Null
        $true
    }
    catch
    {
        $false
    }
}
Get-LAPSExists

I just want to return true if the attribute exists and false if it doesn't. Is there a better way to do it ?

If I just do :

function Get-LAPSExists {
        if (get-ADObject "CN=ms-mcs-admpwd,$((get-adrootDSE).schemaNamingContext)")
        {
              $true
         }
         else
         {
               $false
          }
}

I have an error when attribute doesn't exist ...

Thank you for your return.

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

Rich Matheisen 48,116 Reputation points
2021-01-05T15:57:30.063+00:00

You need the "-ErrorAction STOP" added to the Get-ADObject cmdlet your first script. Without that the Try/Catch is ineffective and the cmdlet throws a non-terminating exception. You need a terminating exception before the "Catch" block will be executed, and the "STOP" will turn any non-terminating exception into a terminating one.

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. matteu31 512 Reputation points
    2021-01-05T16:32:23.26+00:00

    Thank you for your help, I need to continue my powershell formation to manage error.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.