# 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