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

Expanding System Volume C Drive of Windows Hyper-V Virtual Machine

There are three three steps to expand a disk of a virtual machine: Connect to…

Kerberos “Second Hop” Problem

Issue Sometimes, there's a need to run WinRM into a "Jump Box" (trusted host in…

User Account Group Membership Copy

This is the quick snippet to be executed in the context of a Domain Administrator:…