Why are the variable assignments that I make inside the Trap block not visible outside it?
$integer = 0;
$string = [String]::Empty;
$stringBuilder = new-object 'System.Text.StringBuilder';
trap
{
$integer = 1;
$string = '1';
$stringBuilder.Append('1');
write-host "Integer Variable Inside: " $integer;
write-host "String Variable Inside: " $string;
write-host "StringBuilder Variable Inside: " $stringBuilder;
continue;
}
$dummy = 1/$zero;
write-host "Integer Variable Outside: " $integer;
write-host "String Variable Outside: " $string;
write-host "StringBuilder Variable Outside: " $stringBuilder;
I would have expected the results from within and outside the Trap block to be identical but these are the results that I am seeing.
Integer Variable Inside: 1
String Variable Inside: 1
StringBuilder Variable Inside: 1
Integer Variable Outside: 0
String Variable Outside:
StringBuilder Variable Outside: 1
Notice that it is only the StringBuilder that retains its value.
I am guessing that this has something to do with the difference between value and reference types but can't quite pin it down.