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

PowerShell: Get Size On Disk and Discover Largest Files in a Given Directory

# getSizeOnDisk-v0.01.ps1# Set variables$parentDirectory="C:\"$depth=4$topX=10$excludeDirectories="C:\Windows","C:\Program Files","C:\Program Files (x86)"$clusterSizeOfNetworkShare=8192# sanitateif($depth -le 1){$depth=1}################################## Excuting Program as an Administrator…

PowerShell: Passing Local Functions to Remote WinRM Sessions

# Dynamic Credential Method 1 $who = whoami if ($who.substring($who.length-2, 2) -eq "-a"){$username=$who;} else {$username=$who+"-admin";}…

PowerShell: Installing or Including an Application On a Computer or Scripting Session

Sample Usage: PS C:\WINDOWS\system32> includeapp -appName notepadplusplus -appExe notepad++notepadplusplus version 7.91.0.0 already exists.True function includeApp($appName,$appExe=$False,$version){…