Average Rating:

3.50 by 2 users.

25 Downloads, 72 Views

New-TempFile.ps1

By: spinlock 21 Apr 2011 07:01 AM UTC in the category: Advanced Event 10

Description:

Returns a temporary file name. If the -InputObject parameter is specified (or piped in), the contents are written to the temporary file.
Accepts and acts upon -whatif, -encoding, -verbose -debug parameters
Allows the user to specify which directory the tempfile is to be created in.

Optionally displays the contents of the temporary file in notepad once completed (-ShowInNotepad)
#requires -version 2.0 

<#
.SYNOPSIS 
	Returns a temporary file name, and writes any piped input into it.
	
.DESCRIPTION 
	Returns a temporary file name.  If the -InputObject parameter is specified 
	(or piped in), the contents are written to the temporary file.
	
	The file is not deleted.  That is the responibility of the caller.


.EXAMPLE 
    PS> New-TempFile
	C:\Users\UserName1\AppData\Local\Temp\om3fatmv.0k2
	
	Description
	===========
	Returns a Temporary file name, that has been created that is zero bytes long.
	The name of the file is returned, as in this case, "C:\Users\UserName1\AppData\Local\Temp\om3fatmv.0k2"
	
.EXAMPLE 
    PS>  get-process | .\Output-TextFile.ps1 -encoding unicode
	C:\Users\UserName1\AppData\Local\Temp\c00zho1f.jbj
	
	Description
	===========
	Writes the contents of output from get-process to a temporary file.	
	
	
.EXAMPLE 
    PS> gc e:\foo.bar | New-TempFile
	
	Description
	===========
	Writes the contents of e:\foo.bar to a temporary file.	

	
.EXAMPLE 
    PS> gc e:\foo.bar | New-TempFile -encoding Unicode
	C:\Users\userName1\AppData\Local\Temp\ypg0yv2h.fv5
	
	Description
	===========
	Writes the contents of e:\foo.bar to a temporary file.	

.EXAMPLE 
    PS> $Name=(gc e:\foo.bar | New-TempFile.ps1)

	Description
	===========
	Puts the contents of the file e:\foo.bar into a temporary file, the name of the
	temporary file is stored in $Name.
	
.EXAMPLE 
    PS> gc e:\foo.bar | New-TempFile.ps1  -path C:\TEMP
	c:\temp\jqvkqqui.kmw

	===========
	Puts the contents of the file e:\foo.bar into a temporary file, the name of the
	temporary file is returned as c:\temp\jqvkqqui.kmw.
	
	
	
.Notes 
	NAME:      New-TempFile
	AUTHOR:    spinlock
	LASTEDIT:  21/April/2011
	
	It is not true that WindowsPowersHell
	
#>

	param(
		#
		#  The stream of objects to write to the temporary file
		#
		[Parameter(Position=0, Mandatory=$false, ValueFromPipeline=$true)]
		[object] $InputObject,
		# OutputFilePAth = to specify a different directory that the  temporary one	
		[Parameter(Position=1, Mandatory=$false, ValueFromPipeline=$false)]
			[Alias("Path")]
			[string] $FilePath=$null,
		#
		# Specifies whether to open the tempfile created in notepad
		#
		[Parameter(Mandatory=$false, ValueFromPipeline=$false)]
			[switch] $ShowInNotepad=$false,
		#  Encoding of file to output	
		[Parameter(Mandatory=$false, ValueFromPipeline=$false)]
			[ValidateSet("Unicode", "ASCII")]  # We only support Unicode, and ASCIi File formats
			[string] $Encoding="ASCII", 		# Note this is different than the normal default which is UNICODE
		[Parameter(Mandatory=$false, ValueFromPipeline=$false)]
			[switch] $Whatif

	)
	

BEGIN
{
	function get-TempFileName()
	{
		<#
		.SYNOPSIS 
			Returns a temporary filename, extends [system.io.path]::GetTempFileName() as
			it allows you to specify the path where to create the directory
		.DESCRIPTION 
			Checks through the user's temp directory to create a temporary name.
			If the file preexists it will try with a new name.
			
			There is no guarantee that by the time the file is actually created there 
			isn't a file already existing, but the due to the naming a hit should be very unlikely.

		.PARAMETER Path
			The path where to create the file, otherwise User's TEMP directory is used.
		.OUTPUT 
			A unique file name with its path.
		#>
		
		param(
			[Parameter(Position=0, Mandatory=$false)]
				[string] $Path=""
			)
		$MAXITERATIONS = 100
		$i=0
		
		write-debug "Getting temporary filename, path=$path"
		if ($path.length -eq 0)
		{
			# check through TEMP, TMP, and LocalAppData
			foreach ($basepath in ($env:temp, $env:temp,$env:LOCALAPPDATA))
			{
				# is $basepath set, and is it a directory
				if ($basepath.Length -and (test-path -PathType Container -path $basepath))	
				{
					$path = $env:temp
					break 
				}	
			}
			# we've gone through the above, and not found a match so use local dir.
			if ($path.length -eq 0) {$path = "." }	#we'll use the current directory
		}
		
		write-debug ("TEMP Path is $path " + $path.length)
		
		if (-not (test-path -PathType Container -path $Path))
		{
			throw "Path provided is not a valid directory"
		}
		do 
		{
			$filename = join-path $path ([System.IO.Path]::GetRandomFileName())
			$i++
		} until ((-not (test-path $filename)) -or ($i -ge $MAXITERATIONS))
		
		if ($i -ge $MAXITERATIONS)
		{
			throw "Cannot create unique filename"
		}
		
		write-debug	("TEMP filename is" +  $filename)
		write-output $filename
		
	}
	
	
	#
	#  Main section of begin
	#
	
	# Get the unique temporary filename, could use [System.IO.Path]::GetTempFileName() but I like mine because you can
	# specify a path
	$TempFileName = get-TempFileName $FilePath
	
	$DefParams = @{
		Encoding = $Encoding
		Whatif = $Whatif
	}
}

PROCESS {
	Out-File -Append -InputObject $InputObject -FilePath $TempFileName   @DefParams
}

END {
	#  Open the file in notepad - and only if whatif is not specified (if it was there is no file to open)
	if (-not $Whatif -and $ShowInNotepad) { notepad $TempFileName }
	# Return the temporary file name
	$TempFileName
}	
Top

Comments: