Average Rating:

3.50 by 2 users.

29 Downloads, 51 Views

1 Comment(s)

create-tempfile

By: Thomas Paetzold 20 Apr 2011 04:37 PM UTC in the category: Advanced Event 10

Description:

create a temp file that contains data from the pipeline. Ii terminates the pipeline and returns the name of the tempfile. The tempfile will be stored in the temp folder of the users profile.
function create-tempfile
{
<#
.SYNOPSIS
Create a textfile in the users tempfolder. The content is taken from the pipeline.

.DESCRIPTION
This function creates a textfile in the temporary folder of the users profile.
The filename is generated from the day and userinformation. If you create more then
one textfile a day an ongoing number will be added to the textfile. This function doesn´t
delete any older tempfiles. so please be careful in using this function.
Because it only consumes space on the harddisk. The function terminates the pipeline.


.PARAMETER show [Boolean]
After tempfile is created notepd is started with the content of the tempfile.

.EXAMPLE
This example writes the text "hier kommt ein TEST" to the tempfile.

"hier kommt ein TEST" | create-tempfile

#> 


param (
[System.Boolean]$show=$false
)


Begin {
$pipelineisempty=$true
# get Temp folder
$folder= $env:temp
# generate filename
$tmpfile = $tmpfilename= (get-date -UFormat "%Y%m%d")+"_"+$env:USERNAME
$i=1
while (Test-Path ($folder+"\"+$tmpfile+".log")) {
	$postfix = "_"+$i
	$tmpfile = $tmpfilename + $postfix
	$i++
}
$filename = $folder + "\" + $tmpfile + ".log"
}

process {
if ($_ -ne $null) {
	$pipelineisempty=$false
	# the input (Pipeline) is written to a textfile in the tempfolder
	Out-file -filepath $filename -InputObject $_
}
}

End {
if ($pipelineisempty) {
	Write-Host "This function accepts input from the pipeline. No file is generated. Please get help get-help create-tempfile"
} else {
	if ($show) {
		notepad $filename
	}
	return $filename
}
}
}
Top

Comments:

4/20/2011 5:27 PM
Use correct Verbs in function names. i.e. New-TempFile instead of create. Check out my blog post on PowerShell coding styles - http://get-powershell.com/post/2011/04/13/Extra-Points-for-Style-when-writing-PowerShell-Code.aspx