Average Rating:

4.50 by 3 users.

50 Downloads, 204 Views

1 Comment(s)

out-tempfile.ps1

By: mjolinor 21 Apr 2011 10:53 PM UTC in the category: Advanced Event 10

Description:

Creates a temporary (.tmp) file in the system temp directory, and writes pipeline input to the file. Encoding and newlines can be specified by parameters, and will optionally open the file in Notepad after writing. Checks for
interactive user environment before running Notepad, and prompts for verification before opening large files.
Includes support for shouldprocess, provided debug and verbose output.
function out-tempfile {

####################################################################################
<#  
.SYNOPSIS  
    Copies pipline input to a temp file. 
	
.DESCRIPTION  
    Creates a temporary (.tmp) file in the env:temp directory, and copies the pipeline input into it.  
	Uses system.io.streamwriter for performance, and has parameter options for output file
	encoding and newlines. Will optionally open the file in Notepad after writing.  Open with 
	Notepad warns and propmts for verification if the filesize exceeds the $open_warn threshold.
	The Open option is contingent on [environment]:userinteractive to prevent attempting to run 
	the function in a non-interactive (eg scheduled task) environment with that option.
	
.NOTES  
    File Name : Out-TempFile.ps1  
    Requires : PowerShell V2 
	Author: Rob Campbell
	Date: 04/21/2011
	Version: 1.0.0
	
.PARAMETER Encoding
	The Encoding parameter specified the encoding type of the data written to the temp file.
	Valid values are ASCII, Unicode, UTF7, UTF8, UTF32, Bigendianunicode, and default.
	The default value is "default".
	
.PARAMETER NoNewLine
	The NoNewLine parameter specifies whether a newline (CRLF) will be inserted after each
	record read from the pipeline.  This is a switch parameter. Default is to insert newlines.

.PARAMETER Open
	The Open parameter specifies whether the file will be opened in Notepad after being written.
	This parameter is only enabled if [environment]::UserInteractive is $true.  If the file size 
	exceeds the value set in $Open_Warn, you will be prompted to verify that you wish to open the file.

	
.LINK  
    http://blogs.technet.com/b/heyscriptingguy/archive/tags/2011+scripting+games/event+10/advanced/
	
.EXAMPLE  

	Gets the full help from get-childitem, formats it using out-string, writes it to 
	a temp file using ASCII encoding, and then opens the file in Notepad:
	
	Get-Help get-childitem -Full | Out-String  | out-tempfile -Encoding ASCII -Open
	

    
 #>
 
####################################################################################

[CmdletBinding(SupportsShouldProcess=$true)]
		
param(
	[Parameter(Mandatory=$true,valuefrompipeline=$true)]
	[AllowEmptyString()]
	[String[]]
	$inputdata,
	
	[Parameter(Mandatory=$false)]
	[ValidateSet("ASCII","Unicode","UTF8","UTF7","UTF32","BigEndianUnicode")]
	[string]$Encoding="default",
	
	[Parameter(Mandatory=$false)]
	[Alias("Notepad")]
	[switch]$Open,
	
	[Parameter(Mandatory=$false)]
	[switch]$NoNewLine
	)
	
Begin {
		
	# Create temp file and FileInfo object
	[Void]$pscmdlet.shouldprocess($tempfile)
	Write-debug "Temp directory path is $([system.io.directoryinfo]$env:temp)"

	Write-Debug "Creating temp file"
	$tempfile = [System.Io.Path]::GetTempFileName()
	if(-not $?){$pscmdlet.throwterminatingerror($Error[0])}
	
	Write-Verbose "Temporary file is $tempfile"
	Write-Debug "Returning filename $tempfile"
	
	#Return the temporary file fullname
	write-output $tempfile
	
	#Create new streamwriter
	Write-Debug "Creating streamwriter for file $tempfile using encoding $encoding"
	$_encoding = [System.Text.Encoding]::$Encoding
	$stream_writer = New-Object System.IO.StreamWriter $TempFile,True,$_encoding
	
	#byte multipliers used to calculate bytes written for write-debug messages
	if ($Encoding -eq "UTF32"){$byte_multiplier = 4}
	elseif ($Encoding -match "Unicode"){$byte_multiplier = 2}
	else {$byte_multiplier = 1}
	
	#End of Begin block
	}
	
	
Process {
	
	$inputdata | foreach-object {
	write-debug "Writing $($_.length * $byte_multiplier) bytes to $tempfile"
	$stream_writer.Write($_)
	if (-not $NoNewLine){
		write-debug "Writing newline `($(2 * $byte_multiplier) bytes`) to $tempfile"
		$stream_writer.Write($stream_writer.NewLine)
		}
	}
	#End Process block
}
	
End {
	
	#close streamwriter
	$stream_writer.Close()
		
	$tempfile_size = (gci $tempfile).length
	Write-Verbose "Wrote $tempfile_size bytes to $tempfile"
	
	#If $open switch was specified, and this is an interactive session, open temp file in Notpad.
		if ($open -and [Environment]::UserInteractive){
		
		#Warn threshold for filesize if -Open switch is used
		$Open_Warn = 20MB
		
		$Open_verify = "Y"
		
		if ($tempfile_size -gt $Open_Warn){
			$Open_verify = $null
			while ($open_verify -notmatch "Y|N"){
			$Open_Verify = Read-Host "Temp file is $tempfile_size bytes.`n Do you really want to open that in Notepad? (Y/N)"
			}
		}
		if ($Open_verify -eq "Y"){
			Start-Process "notepad" -ArgumentList $tempfile
			}
		}
	}
	
}
Top

Comments:

4/22/2011 12:20 AM
very nice script. I like your use of gettempfilename