Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access variables defined in try catch scope in Powershell

Tags:

powershell

I have below piece of code , where I am trying to access a variable defined in try but it's not accessible , what could be done to fix it.

  try{
       $X = get-X 
     }
  catch
     {
            Manage exception
     }

   write-host $X
like image 598
VarunVyas Avatar asked Oct 25 '25 09:10

VarunVyas


1 Answers

I just ran into this and it looks like a bug. Declaring the variable outside try block does not solve the scope issue. As soon you leave the try block value of $a gets reset to what it was before you entered try block. so if you want to access $a after executing try{} you need to access it as $global:a inside the try {} block.

like image 107
John Smith Avatar answered Oct 28 '25 01:10

John Smith