1

i know that I can check if a variable exists with

if ($null -eq "aaa"){set-variable -name "aaa"}

Can someone eplain why I never get into any catch block if I try this

try
{
   Get-Variable -Name 'aaa'
}
catch [System.Management.Automation.ItemNotFoundException]
{
   Set-Variable -Name 'aaa'
}
catch
{
   Set-Variable -Name 'aaa'
}
mklement0
  • 382,024
  • 64
  • 607
  • 775
staphylea
  • 11
  • 1
  • 4
    Use `Get-Variable -Name aaa -ErrorAction Stop` or set `$ErrorActionPreference = 'Stop'` – Mathias R. Jessen Feb 10 '20 at 12:39
  • In short: `try` / `catch` only acts on _terminating_ errors, whereas `Get-Variable` with the name of a nonexistent variable name emits a _non-terminating_ error by default, hence @MathiasR.Jessen's suggestion to promote it to a terminating one as shown. See the linked post for more information. – mklement0 Feb 10 '20 at 13:11

0 Answers0