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.
improve powershell function
matteu31
512
Reputation points
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
Answer accepted by question author
1 additional answer
Sort by: Most helpful
-
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.