Tuesday, 7 February 2012

Test-FileOpen

  1. <# 
  2. .SYNOPSIS 
  3.     This script defines a function that tests to 
  4.     see if a file is open. 
  5. .DESCRIPTION 
  6.     This script used the System.Io.FileStream class  
  7.     and the FileInfo class to try to open a file 
  8.     stream for write. If it fails, we return $false
  9.     else we close the file and return $True 
  10. .NOTES 
  11.     File Name  : Test-FileOpen.ps1 
  12.     Author     : Thomas Lee - tfl@psp.co.uk 
  13.     Requires   : PowerShell Version 2.0 
  14. .LINK 
  15.     This script posted to: 
  16.         http://www.pshscripts.blogspot.com 
  17. .EXAMPLE 
  18.     Psh[Cookham8:C:\foo]> $file = New-Object -TypeName System.IO.FileInfo C:\foo\doc1.docx 
  19.     Psh[Cookham8:C:\foo]>Test-FileOpen $file 
  20.     True 
  21. #> 
  22.  
  23. Function Test-FileOpen { 
  24.  
  25. Param ( 
  26. $fileName = $(Throw '***** No File specified')  
  27.  
  28. $ErrorActionPreference = "SilentlyContinue" 
  29. [System.IO.FileStream] $fs = $file.OpenWrite();  
  30. if (!$?) {$true
  31. else {$fs.Dispose();$false
  32.  
  33. # Test the function 
  34. $file = New-Object -TypeName System.IO.FileInfo C:\foo\doc1.docx 
  35. Test-FileOpen $file 

No comments: