|
Multiple trap handlers in a function: variable scoping issues
I'm trying to write the PowerShell equivalent of this:-
void MyMethod ()
{
FileInfo fi = null;
try
{
fi = new FileInfo (@"C:\out.txt");
}
catch (Exception ex)
{
MessageBox.Show (ex.Message);
return;
}
FileInfo fi1 = null;
try
{
fi1 = new FileInfo (@"C:\out1.txt");
}
catch (Exception ex)
{
MessageBox.Show (ex.Message);
return;
}
// use 'fi' and 'f1'; e.g. read their Exists properties
MessageBox.Show (fi.Exists.ToString ());
MessageBox.Show (fi1.Exists.ToString ());
}
-------------------------------------------------------
So far I have this:-
function Main
{
new-variable fi -value $null -option "AllScope"
&{
trap
{
write-host "Exception handler 1" + $_.Exception.Message
continue
}
.{
$fi = new-object -typename System.IO.FileInfo -argumentlist "C:\out.txt"
}
}
if ($fi -eq $null)
{
return
}
new-variable fi1 -value $null -option "AllScope"
&{
trap
{
write-host "Exception handler 2" + $_.Exception.Message
continue
}
.{
$fi1 = new-object -typename System.IO.FileInfo -argumentlist
"C:\out1.txt"
}
}
if ($fi1 -eq $null)
{
return
}
write-host $fi.Exists
write-host $fi1.Exists
}
.. Main
write-host $fi.Exists
write-host $fi1.Exists
-------------------------------------------------------
I.e.
- use script blocks in order to have multiple trap handlers in the same
function
- use the new-variable cmdlet with the "AllScope" option to ensure that
'fi' and
'fi1' exist at function scope and script block scope
Unfortunately, "AllScope" means just that. Hence the two write-host
statements after
the call to Main do work, but ideally they should not.
Am I on the right track? Is there a way to keep the two variables at
function scope?
Is there a fundamentally better/different way than my approach?
TIA
Andrew |