Parsing error messages

I wanted to reduce the amount of verbiage in an error message. I came up with this.


$ScriptName = $MyInvocation.MyCommand.Name # gets name of the script that is running
$Error.clear()
# Introduce an error for testing
Stop-Process -Name invalidprocess -EA "SilentlyContinue"
If ($Error) {
$E1 = $E2 = $E3 = $E4 = $E5 = " " #Sets variables to null.
$E1 = [string]$Error.Exception #Catches error
$E2 = $E1.Split(":") # divides the string at the :
$E3 = $E2[1] # Selects the part of the string after the :
$E4 = $E3.Split("\.") # divides the result at the period
$E5 = $E4[0] # selects the first part of of the string
# Write-Log -Message "$ScriptName $E5" -Path $LogPath warn # writes the result to the log
# Break # exits the script
}
Write-Host $E5

For some reason the above script has stopped working. It appears that something has changed in PS ver 2 on Windows 7 at least.
If the above does not work try this:

 


Function err {
If ($Error) {
$E1 = $E2 = $E3 = $E4 = " " #Sets variables to null.
[string]$E1 = $Error #Catches error
[string]$E2 = $E1.split(":") # divides the string at the ":"
$E3 = $E2.split(".") # divides the string at the "."
$E4 = $E3[0] # Selects the part of the string before the "."
Write-Host $E4
}
$Error.clear()
}