Пишу скрипт удаления некоторых веток реестра. В одном месте нужно отловить исключение:
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
}
}
}
DenTNT недавно публиковал (посмотреть все)
- C#: Добавить поддержку перезапуска приложения - 21.02.2025
- EVE-Online: Отобразить информацию о соединении и fps - 20.02.2025
- WPF: Отображение прогресса с помощью async/await - 13.02.2025