jeudi 30 juin 2016

Powershell nesting vs try/catch

I think I am going at this in the right way, but it doesn't seem to work. Im trying to nest if/elseif/then to loop some commands based on a response. Would this be more correct in a try/catch setup?

here is the code.. (hopefully I can do this right!)

$ecuPort = new-Object System.IO.Ports.SerialPort COM8,9600,None,8,one
$ecuPort.Open()

# Set OBD Mode/PID
$obdMode = "27"                                      # Mode
$obdPid = "02"                                       # PID  change value to 1 to get the seed 
# ----------------------
[int]$i = '1'                                        #  Counter Start

:keyLoop for ( $i -le '65535') {  

$key  = "{0:X}" -f [int]$i                           # ---- Loop setup----
$request = $obdMode + $obdPid + $key.PadLeft(4,"0")
$ecuPort.Write($request)                             # ---Send Request---
start-sleep -m 400
$input = $ecuPort.ReadExisting() # -split " "          # ---Get Response----  
$response = $input[2,3] -join ""

}
 if ($response -eq '35') {                           # ----Main Logic-----

  $key | Add-Content KeyLogger.txt                  # Log failed keys for testing
  $i++                                              # advance key counter
  Start-Sleep -m 11000                              # 10 second delay
  continue keyLoop 
 }
  elseif ($response -eq '34') {

   Write-Host("Unlock Key:") $key
   $key | Out-File Unlocked.txt
   # blink led
   $ecuPort.Close()
   break  
}  
 elseif ($response -eq '36') {

   $arduPort.Open()
   Start-Sleep -m 400
   $arduPort.Write("off")
   Start-Sleep -m 5000
   $arduPort.Write("on")
   $arduPort.Close()
   continue keyLoop
  }   
   elseif ($response -eq '37') {
   Start-Sleep -Milliseconds 11000
   continue keyLoop
  }
   then {

      # TBD return

        }

Im still learning so go easy on me, I realize this is pretty basic stuff, but I am weak on syntax still. Im trying to run the script block for each if, then continue to the start ':keyLoop label' to cycle through. Hence the continue statements. Never seems to run the code within the loop! Thanks

Aucun commentaire:

Enregistrer un commentaire