Post by Keith HillPost by Keith Hill [MVP]I think the "non-determinism" you are seeing are the resulting of the
garbage collector sporadically closing the "for you".
I think the "non-determinism" you are seeing is the result of the
garbage collector sporadically collecting and closing the file "for you".
Since you don't close the file explicitly the file won't get closed until
the GC notices that the FileStream object that you created during the
previous script execution is no longer needed and finalizes it (which closes
the underlying file hanlde).
--
Keith
When the script runs it sometimes reports a locked file and sometimes
it doesnt, this is probably the "garbage collector" as you say,
however whilst that shell is still open the file remains locked to
other process. the only way to clear the lock is to end the shell.
an alternate method would be to use an trap handler to close the
stream on a file already open error. something like below. Does anyone
know what type of an exception this error is?
"
New-Object : Exception calling ".ctor" with "4" argument(s): "The
process cannot access the file 'C:\test.lck' because it is being used
by another process."
At C:\test.ps1:15 char:26
+ $script:test = new-object <<<< System.IO.FileStream("test.lck",
[System.IO.FileMode]::Open, [System.IO.FileAccess]::
Read, [system.Io.FileShare]::None)
"
then I could do something like this (i dont know wht the exception
type is?)
Trap [Exceptiontype] { Write-Host "file in use" -foregroundcolor red;
$Script:lck.close(); Exit }
$Script:lck = New-Object System.IO.FileStream("test.lck",
[System.IO.FileMode]::Open, [System.IO.FileAccess]::Read,
[system.Io.FileShare]::None)
then if the script errors before it finishes the trap handler will
close the stream