PowerShell: Не ловится исключение

Пишу скрипт удаления некоторых веток реестра. В одном месте нужно отловить исключение:

foreach ($str in $registryExtensionPathFor_Print)
{
  $newRegPath = "HKLM:\SOFTWARE\Classes\" + $str + "\shell\print\command"
  $result = Test-Path ($newRegPath)
  if ($result)
  {
    try
    {
      Remove-Item -Path $newRegPath 
    }
    catch [System.Security.SecurityException]
    {
      Write-Output $_.Exception.Message
    }
  }
}

Но исключение не ловится:

Remove-Item : Requested registry access is not allowed.
At D:\Distr-free\System\Tweaks\PowerShell\Current.ps1:195 char:11
+ Remove-Item -Path $newRegPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (HKEY_LOCAL_MACH…cut\shell\print:String) [Remove-Item], SecurityException
+ FullyQualifiedErrorId : System.Security.SecurityException,Microsoft.PowerShell.Commands.RemoveItemCommand

Чтобы оно в итоге поймалось, нужно к Remove-Item дописать -ErrorAction Stop.
Код получится таким:

foreach ($str in $registryExtensionPathFor_Print)
{
  $newRegPath = "HKLM:\SOFTWARE\Classes\" + $str + "\shell\print\command"
  $result = Test-Path ($newRegPath)
  if ($result)
  {
    try
    {
      Remove-Item -Path $newRegPath -ErrorAction Stop
    }
    catch [System.Security.SecurityException]
    {
      Write-Output $_.Exception.Message
    }
  }
}


Подписаться
Уведомление о
guest
0 Комментарий
Inline Feedbacks
View all comments