PowerShell Error Trapping

Error trapping in forms isn't much different than other error trapping in PowerShell.

I placed this here due to the fact that when using forms you are usually looking for

user input which can cause issues in a script.

0) One of the first and foremost things to use when writting scripts is to use the Try / Catch.


                Get-aduser ScottHead -Properties * | Select * -ErrorAction Stop
                write-host $_.Exception.Message

1) Cleaning data, I run multiple forms and one of the best practice for any type of programming is clearing your variables.

I do this by a simple double quote statement as shown below or use PowerShell command.

        #------ Run at beginning fo Script-----
        #--------- or try Clear-Variable ----------
        Clear-Variable MyVaribale





2) Verify that a field was not left blank using a function that I pass all form input to.
I also use $Null instead of "" for checking for blank / null data returns. 


  #----------Function used to check data fields so they are not blank and do not contain Apostrophies------------------
    Function DataChecker {
        Param ([string]$MyString)
          If($MyString -eq "")
             Write-Host "-------------------Input Stop Error - No Work Has Been Done - : Field is Blank------------" -foregroundcolor "magenta"
        ElseIf($MyString.Contains("'") -eq $true)
             Write-Host "-------------------Input Stop Error - No Work Has Been Done - : Illegal Char Apostrophe ---------------" -foregroundcolor "magenta"
             write-host "Variable Passed Checks:" $MyString
        #-------- The call to the function for field FirstName -------------
        DataChecker $FirstNameInfo 




3) I also use the trim feature when gathering input because AD will hold a white

space and that makes serious issues when passwords or SAM Account Names are entered. 


    $FirstNameInfo=" Scott "
    #Trim White Spaces on Input




4) I also use items to verify if length is correct for example the minimum password char length is 8.

$Password ="Que$!!"

    if($Password.Length -lt 8){
        Write-Host "---Input Stop Error - No Work Has Been Done - : Password is to Short-----" -foregroundcolor "magenta"

2020 | Scott W. Head  |  Sr. Systems Admin | Certified Microsoft Windows Server Administrator