Try catch difference between powershell 5 and 7 activeDirectory module

Hi I’m using a try catch block

$admins = import-csv 'C:\Users\onboarding_it.gen\Documents\temp\offboarding_db.csv'

#if the user has an ADM account and set the account expirationdate on this adm account.
foreach($admin in $admins){

    
    $testuser = $admin.Email
    $SamAccount = $testuser.split("@")
    $AdmSamAccount = $SamAccount[0]
    $AdmSamAcct = $AdmSamAccount +'.adm'
    try{
    $test = get-aduser -identity $AdmSamAcct -properties samaccountname
        if($test){
            set-aduser -identity $AdmSamAcct -AccountExpirationDate $expiredate
        }
    }catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
        
        Write-Output "This user with samaccount $($AdmSamAccount) has no adm account"
    }
}

and in Powershell 5 the ADIdentityNotDFoundException is working correctly but I get an error under powershell 7
Get-ADUser: Cannot find an object with identity:

If search in powershell 5 for this exception I type in [ADIdentityNotDFoundException followed by tab I get Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException

how do I find the correct syntax in powershell 7

Hey acer4605,

tested snippet of your script on my end, seems to work with powershell 7.

i think if identity is missing, get-aduser throws a terminating error. The catch block will pick it up. i have my erroractionpreference set to continue.

e.g. below catch block picks up

try {
    get-aduser -identity someusernotonad
}
catch {
    Write-Host 'user not found' -ForegroundColor Yellow    
}

The syntax is the same [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
run get-error on powershell 7, see examples below.

another issue that I see is that when I try to import the activeDirectory Module I get this warning

 import-module ActiveDirectory
WARNING: Module ActiveDirectory is loaded in Windows PowerShell using WinPSCompatSession remoting session; please note that all input and output of commands from this module will be deserialized objects. If you want to load this module into PowerShell please use 'Import-Module -SkipEditionCheck' syntax.
PS C:\Users\onboarding_it.gen>

when I use the skipEditionCheck I get this error message

import-module -skipEditionCheck ActiveDirectory
Import-Module: Could not load type 'System.Management.Automation.PSSnapIn' from assembly 'System.Management.Automation, Version=7.3.1.500, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

this is in my opinion also the reason that the tabcompletion is not working when typing in

[ADIdentityNotFoundException and try to use tab completetion which does not give me any result

any thoughts on how to solve this? I’m running this on a 2016 windows server edition

found this when I searched the error.

ActiveDirectory with Powershell 7 on Windows Server 2016 - Microsoft Q&A