Posted On July 10, 2020

PowerShell: Get Try Catch Exception Type of a Function

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Get Try Catch Exception Type of a Function
# This function will return the exception type so that it could be specified on while reiterating though codes and provide specific responses to exceptions
# e.g: catch [System.Management.Automation.MethodInvocationException]

$serverName='ad01.kimconnect.net'
$scriptString="new-pssession $serverName"

function getException($scriptString){
    $ErrorActionPreference='stop'
    Try {
        if($scriptString.gettype() -eq [string]){
            invoke-expression $scriptString
            }
        else{$scriptString.Invoke()}
        write-host 'No errors detected.'
        return $null
        }
    Catch{
        return $Error[0].Exception
        }
}

function generateRandomPassword{
    param(
        $minLength = 8,
        $maxLength = 16,
        $nonAlphaChars = 2
    )
    add-type -AssemblyName System.Web
    # Preempt this error
    #Unable to find type [System.Web.Security.Membership].
    #At line:1 char:1
    #+ [System.Web.Security.Membership]::GeneratePassword(24,5)
    #+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    #+ CategoryInfo          : InvalidOperation: (System.Web.Security.Membership:TypeName) [], RuntimeException
    #+ FullyQualifiedErrorId : TypeNotFound
    $randomLength = Get-Random -Minimum $minLength -Maximum $maxLength    
    $randomPass = [System.Web.Security.Membership]::GeneratePassword($randomLength, $nonAlphaChars)
    return $randomPass
}

getException $function:generateRandomPassword
getException $scriptString

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

How to Restart Domino Services without Reboot

--------------Restart_Domino.bat------------------------------------------------------net stop "Lotus Domino Server (LotusDominoData)"c:\bats\pulist | findstr /I /C:"nadminp.exe" >c:\bats\pid.lstc:\bats\pulist | findstr /I /C:"naldaemn.exe"…

Python Module: JSON

Overview JavaScript Object Notation (JSON) is written in plain-text that is very useful to store…

PowerShell: Fix Email Aliases as Preparation for O365 Migration

Check SMTP Addresses of On Premise Mailboxes function checkSmtpAddresses{ $microsoftDomain1="@kimconnect.mail.onmicrosoft.com" $microsoftDomain2="@kimconnect.onmicrosoft.com" $dotLocal=".local" $onpremMailboxes=Get-Mailbox -ResultSize unlimited…