Thursday, 15 July 2010

Copy-File2.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script creates a file, then reads it and displays the output. 
  4. .DESCRIPTION 
  5.     This script implements the MSDN sample for this page. It first creates a file (assuming the file 
  6.     does not already exist) and writes three lines to it. The script then opens the file, reads each 
  7.     line and displays it.    
  8.      
  9. .NOTES 
  10.     File Name  : Copy-File2.ps1 
  11.     Author     : Thomas Lee - tfl@psp.co.uk 
  12.     Requires   : PowerShell Version 2.0 
  13. .LINK 
  14.     This script posted to: 
  15.         http://pshscripts.blogspot.com/2010/07/copy-file2ps1.html
  16.     MSDN Sample posted at: 
  17.         http://msdn.microsoft.com/en-us/library/system.io.file.aspx        
  18.         http://msdn.microsoft.com/en-us/library/system.io.file.createtext.aspx
  19.         http://msdn.microsoft.com/en-us/library/system.io.file.opentext.aspx
  20. .EXAMPLE 
  21.     PSH [C:\foo]: . 'E:\PowerShellScriptLib\System.Io.File\Copy-File2.PS1' 
  22.     Hello 
  23.     And 
  24.     Welcome  
  25. #> 
  26.    
  27. # Set name of file to use for this script 
  28. $path = "c:\foo\MyTest.txt" 
  29.    
  30. # Create the file if it does not already exist 
  31. if (![System.IO.File]::Exists($path))  { 
  32.   $sw = [System.Io.File]::CreateText($path
  33.   $sw.WriteLine("Hello"
  34.   $sw.WriteLine("And"
  35.   $sw.WriteLine("Welcome"
  36.    
  37. # Open the file to read from and set $s to an empty string 
  38. $sr = [System.Io.File]::OpenText($path
  39. $s = ""
  40.  
  41. # Loop through the file, line at a time and display the output 
  42. while (($s = $sr.ReadLine()) -ne $null)  { 
  43.   $s 
  44.   
  45. # And close the reader/writer 
  46. $sw.Close() 
  47. $sr.Close() 

2 comments:

Stephen Bach said...

This script works as advertised if you move Line 48 to follow Line 35.

Thomas said...

Seems to work here without moving the lines around.