try catch - not as expected


hello,
 i struggle with  try catch sequences,
 where failure?

thank comments
erhy

#test_path_in_registry
function regkeyhklmexists ( [string]$regp ) {
  $found = $false
  $acceptederr = $false
  try {
    $private:o = get-item -path $regp # why error messages when in try sequence?
  }
  catch [pathnotfound] { # exception never catched in tests
    out-host -inputobject ( 'catched: pathnotfound' )
  }
  catch [system.security.securityexception] { # exception never catched in tests
    out-host -inputobject ( 'catched: system.security.securityexception' )
  }
  catch { # catched if 1 catch statement
   if ( 'pathnotfound' -eq $_.exception.gettype() ) {
     $acceptederr = $true
     out-host -inputobject ( 'not found' )
   }
   elseif ( 'system.security.securityexception' -eq $_.exception.gettype() ) {
     $acceptederr = $true
     out-host -inputobject ( 'access denied' )
   }
   else {
     write-host -inputobject ("error text: " + $_ )
     write-host -inputobject ("exception: " + $_.exception.gettype() )
   }
  }
  { # works
    out-host -inputobject ( 'finally after try get-item -path' )
  }
  if ( $private:o -is [object] )  {
    $found = $true
  } 
  return $found
}
#
regkeyhklmexists 'hklm:\software\microsoft\windows nt\currentversion\schedule\taskcache\tree\tomtomhomex'

powershell has 2 types of errors terminating , no-terminating. try/catch works on terminating errors. command using of non-terminating type change can use -erroraction param , set value stop, cause command have terminating errors or can change session terminate setting $erroractionpreference = stop , errors terminating. hope helps. good-times , get-command.


Windows Server  >  Windows PowerShell



Comments

Popular posts from this blog

Error: 0x80073701 when trying to add Print Services Role in Windows 2012 Standard

difference between wuauclt1.exe and wuauclt.exe

Windows 2016 RDS event 1306 Connection Broker Client failed to redirect the user... Error: NULL