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. # Open the file to read from. 
  50. $sr = $fi1.OpenText() 
  51. $s = ""
  52. "Original file:";"-----------" 
  53. while (($s = $sr.ReadLine()) -ne $null) { 
  54.     $s 
  55. "-----------"
  56. try { 
  57.     $path2 = [System.IO.Path]::GetTempFileName() 
  58.     $fi2 = New-Object system.IO.FileInfo $path2 
  59.  
  60.     # Ensure that the target does not exist. 
  61.     $fi2.Delete() 
  62.  
  63.     # Copy the file 
  64.     $result = $fi1.CopyTo($path2
  65.  
  66.     "{0} was copied to {1}" -f $path, $path2 
  67.  
  68.     # Delete the newly created file. 
  69.     $fi2.Delete() 
  70.     "{0} was successfully deleted." -f $path2 
  71. }  
  72. catch { 
  73.     "The process failed:";$Error[0] 
  74. # End of Script 
  75. "-----------" 

No comments: