Tuesday, 6 October 2009

Create-TempFile.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script creates then copies a file using 
  4.     System.IO.Fileinfo.CopyTo() 
  5. .DESCRIPTION 
  6.     This script first creates a temporary file, then 
  7.     copies it to another file then deletes the  
  8.     second file. 
  9. .NOTES 
  10.     File Name : Create-TempFile.ps1 
  11.     Author : Thomas Lee - tfl@psp.co.uk 
  12.     Requires : PowerShell V2 
  13. .LINK 
  14.     This script posted to: 
  15.     http://pshscripts.blogspot.com/2009/10/create-tempfile.html
  16.     MSDN Sample posted at: 
  17.     http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx 
  18. .EXAMPLE 
  19.     PSH [C:\foo]: .\Create-TempFile.PS1' 
  20.     File C:\Users\tfl\AppData\Local\Temp\tmpF2C1.tmp exists 
  21.     Original file: 
  22.     ----------- 
  23.     Hello 
  24.     And 
  25.     Welcome 
  26.     ----------- 
  27.     C:\Users\tfl\AppData\Local\Temp\tmpF2C1.tmp was copied to C:\Users\tfl\AppData\Local\Temp\tmpF2E1.tmp 
  28.     C:\Users\tfl\AppData\Local\Temp\tmpF2E1.tmp was successfully deleted.    
  29. #> 
  30.   
  31. ## 
  32. # start of script 
  33. ## 
  34.    
  35. # Create temp file and FileInfo object  
  36. $Path = [System.Io.Path]::GetTempFileName() 
  37. $fi1 = New-Object System.Io.FileInfo $Path 
  38.  
  39. # See if file exists 
  40. if ((Ls $fi1)) { 
  41.     "File {0} exists" -f $fi1  
  42.     # Create a file to write to and write to it 
  43.     $sw = $fi1.CreateText() 
  44.     $result=$sw.WriteLine("Hello") 
  45.     $result=$sw.WriteLine("And") 
  46.     $result=$sw.WriteLine("Welcome") 
  47.     $sw.Close() 
  48. } 
  49.   
  50. # Open the file to read from. 
  51. $sr = $fi1.OpenText() 
  52. $s = ""; 
  53. "Original file:";"-----------" 
  54. while (($s = $sr.ReadLine()) -ne $null) { 
  55.     $s 
  56. } 
  57. "-----------"
  58. try { 
  59.     $path2 = [System.IO.Path]::GetTempFileName() 
  60.     $fi2 = New-Object system.IO.FileInfo $path2 
  61.  
  62.     # Ensure that the target does not exist. 
  63.     $fi2.Delete() 
  64.  
  65.     # Copy the file 
  66.     $result = $fi1.CopyTo($path2) 
  67.  
  68.     "{0} was copied to {1}" -f $path, $path2 
  69.  
  70.     # Delete the newly created file. 
  71.     $fi2.Delete() 
  72.     "{0} was successfully deleted." -f $path2 
  73. }  
  74. catch { 
  75.     "The process failed:";$Error[0] 
  76. } 
  77. # End of Script 
  78. "-----------" 

No comments: