Average Rating:

4.50 by 2 users.

24 Downloads, 70 Views

2 Comment(s)

New-TempFile

By: Matthew Painter 21 Apr 2011 12:57 PM UTC in the category: Advanced Event 10

Description:

Advanced Event 10 in the 2011 Scripting Games uses Windows PowerShell to create an advanced function to create temporary files.


function New-TempFile {
<#
    .Synopsis
       Create new temp file
    
    .Description
       New-TempFile creates a new temp file and sets its value.
       
       The temp file created uses the following naming convention:
       tmp*.tmp where * is a random 4 digit hex number between 0 and FFFF
       New-TempFile has the ability to create 65535 different file names.
       
       You can manually specify a folder to use or the script will 
       default to the current user's %temp% path.    
       
       New-TempFile returns the path to the new temp file created.   
                                    
    .parameter inputObject
       Specifies the value of the new temp file. You can also pipe 
       a value to New-TempFile
                       
    .parameter folder
       Specifies the target folder for the new temp file. 
       Only an existing directory name is to be specified.
       (Note: The file name is randomly generated)        
                                     
    .parameter Open
       Display the content of the temp file in notepad. 
                              
    .parameter encoding
       Specifies the type of character encoding used in the file. 
       Valid values are "Unicode", "UTF7", "UTF8", "UTF32", "ASCII", 
       "BigEndianUnicode", "Default", and "OEM". 
       "ASCII" is the default.
       
    .parameter Confirm 
       Prompts you for confirmation before executing the command.
    
    .parameter WhatIf 
       Describes what would happen if you executed the command without actually executing the command.                      
      
  
   .Example
       "ABC" | New-TempFile
       
    Description
    -----------
       Creates a new temp file with the content "ABC"
       File is saved in current users temp folder
       Character encoding is ASCII
       Returns the path to the new temp file
         
   .Example
       (dir c:) | New-TempFile -folder c:\logs -encoding unicode -open 
       
    Description
    -----------
       Creates a new temp file with sample content.
       Temp file is saved in c:\log\ folder
       character encoding is unicode
       Contents of new temp file are displayed in notepad.
       Returns the path to the new temp file.
       
           
    .Inputs
       system.string
       content to be saved to temp file
    .Outputs
       system.string 
       Path to temp file created
           
    .Notes
       NAME:      New-TempFile
       PURPOSE:   2011 scripting Games 
       EVENT:     2011 Adv event 10
       VERSION:   1.0
       AUTHOR:    Matthew Painter
       LASTEDIT:  15/April/2011
       
    .link
       http://bit.ly/hUGXmv            
#>

  
   [CmdletBinding(
      SupportsShouldProcess = $true,
      ConfirmImpact = "low"
      )] 

   param(   
            
      [Parameter( 
      Mandatory=$true,
      Position=0,
      HelpMessage="      Specifies the objects to be written to the file.` 
      E.g. a quoted string or variable that contains object(s)",
      ValueFromPipeline=$true)]
      [object]$inputObject,   
      
      [Parameter( 
      Mandatory=$false,
      ValueFromPipeline=$false)]
      [string]$Encoding = "ASCII",      
                  
      [Parameter( 
      Mandatory=$false,
      Position=1,
      ValueFromPipeline=$false)]
      [string]$folder = $env:temp,
      
      [Parameter( 
      Mandatory=$false,
      ValueFromPipeline=$false)]
      [switch]$Open
   )
    

   Begin 
   {
            
      $inputObjectArray = @()
      $count = 0
    
      if (Test-Path $folder -pathtype container) 
      {

         if (($folder.substring($folder.length-1, 1)) -eq "\") 
         {
            $folder = $folder.substring(0,$folder.length-1)
            
            Write-Verbose "Info - Trailing slash removed from destination folder:`n$folder"
         }
         
                   
         
         # Instead of using [System.Io.Path]::GetTempFileName() to create the temp file. 
         # I decided to do it manually because I only want filename at this point.
         
         do 
         { 
            $path = "$folder\tmp$("{0:X}" -f (Get-Random -max 65535)).tmp"             

            if (!(Test-Path $path)) { break } else { $count ++ }            
            
         } until ($count -eq 65535)  
                 
         Write-Verbose "Info - Destination temp file path is:`n$path"

      } 
      else 
      {
         Write-Warning "Error - Destination folder path does not exist:`n$folder"
         break
      }
      

      try 
      {      
         Write-Debug "Create new empty temp file?`n$path"
         
         $output = New-Item -ItemType 'file' -Path $path -ErrorAction 'stop' 
                 
         Write-Verbose "Empty temp file created"                   
      } 
      catch 
      {
         Write-Warning "Error - Failed to create temp file:`n$path"         
         Write-Warning $Error[0].Exception.Message 
         break
      }   
   }   
   Process 
   { 
      $inputObjectArray += $inputobject
   }   
   End 
   {
      Write-Debug "Write Contents to temp file?"
      
      Out-File -filepath $path -encoding $encoding -inputObject $inputObjectArray
      
      Write-Verbose "Contents written to file" 
      
      
      if ($open)
      { 
         if (!($PSBoundParameters['whatif'])) 
         {               
            if (Test-Path $path)
            {
               Write-Debug "Open temp file?"
                              
               Invoke-Expression "notepad $path" > $null
            }
         }
         else
         {
            Write-Output "What if: Performing operation `"Open File`" on Target `"Destination: $path`"."
            break   
         }
      }         
      Write-Output $path   
   }
}
Top

Comments:

4/22/2011 7:40 AM
I like this script. You meet requirements, and the extra's as well. I am still not certain why you decided to manually create the temp file name but that is a pretty cool idea using get-random ... i think it is more work than required however. I like your error handling, parameters, and comment based help. good job.
4/22/2011 7:52 AM
Thanks Ed, You have really made my day.