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

Disconnecting from a Windows Server 2012 R2 file sharing session on a Windows 7,8,10 machine

Event ID 64,77,1008 Certificates Events Windows Server 2008, 2008R2