$port= new-Object System.IO.Ports.SerialPort COM1,115200,None,8,One
$port.ReadTimeout = 10000
$port.Open()
$port.WriteLine("admin")
while($myinput = $port.ReadLine())
{
$myinput
}
With this, I get the exception:
Exception calling "ReadLine" with "0" argument(s): "The operation has
timed out."
At C:\Frank\Script\serial.ps1:16 char:32
+ while($myinput = $port.ReadLine <<<< ())
+ CategoryInfo : NotSpecified: (:) [],
MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
How do I handle this exception?
I am fairly new to PS.
Regards,
Frank
IMO, the try/catch/finally in v2 is much more straight-forward:
$port= new-Object System.IO.Ports.SerialPort COM1,115200,None,8,One
$port.ReadTimeout = 10000
$port.Open()
$port.WriteLine("admin")
try
{
while($myinput = $port.ReadLine())
{
$myinput
}
}
catch [TimeoutException]
{
# Error handling code here
}
finally
{
# Any cleanup code goes here
}
# Execution resumes here
However, if you're using v1 then you have to use the trap keyword, I
forget where I got this code originally, but I find it pretty handy:
# Create a new dotted scope for error handling purposes
. {
. { # Here we enter the dotted "Try" code script block
#ENTER CODE TO "TRY" HERE
} # End try script block
trap {
#ENTER "CATCH" ERROR HANDLING CODE HERE
} # End Trap Block
# Execution will resume HERE after trap blocks have executed
# ENTER "FINALLY" CODE HERE
} # End Try/Trap script block
I hope that's not too cryptic. For more info you can use
get-help about_try_catch_finally
get-help about_trap
~Clint