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

Front End Web Development Menu 2019

Deployment Register a domain name: Google Domains, GodaddyManaged or Shared hosting: AWS, Hostgator, InmotionFTP/SFTP: Filezilla,…

Nginx Apache SSL Example

-------------- NGINX -> ** /etc/nginx/sites-available/domainx.conf**server {listen 80;servername xxxxx.domainx.com;return 301 https://$host$requesturi;}server {listen 443 ssl;servername xxxxx.domainx.com;sslcertificate /etc/nginx/ssl/cert_domainx.crt;sslcertificatekey…

JavaScript Challenge: Counting Words

This is useful to render word clouds, emphasizing more commonly occurring words in a database.…