Average Rating:

5.00 by 2 users.

33 Downloads, 79 Views

1 Comment(s)

Advanced10_2011.ps1

By: Albert Fortes 21 Apr 2011 09:57 AM UTC in the category: Advanced Event 10

Description:

Sends output to a temporary file.
#requires -version 2.0

<# 
.SYNOPSIS 
   	Sends output to a temporary file.

.DESCRIPTION
	
	This script sends the output to a temporary file.
	It returns an string with the temporary file path.
	
	Features:
	- Supports common arguments: Verbose, Whatif and Debug.
	- Can specify different encondings.
	- Can display the generated data using the default txt application.
	- Ensures that the temporary file name doesn't exist (unique name). If exist retries, by default 10 times, to get a free one. 
	- By default it will store the to the Temporary directory (%TEMP% variable). Different Path can be assigned.
		
.NOTES 
    File Name  : Advanced10_2011.ps1 
    Author     : Albert Fortes Ribot albert.fortes@gmail.com

.PARAMETER InputObject
	Specifies the objects to be written to the file. The value can be an object, such as a quoted string,
	a variable that contains objects, or a command or expression that gets objects.
	You can also pipe objects to the Out-TempFile cmdlet.

.PARAMETER Path
	Location under the directory that will host the temporary file. By default is '$env:TEMP' folder.

.PARAMETER Encoding
	Specifies the Enconding ot the file text that will store the collected information. The default is 'ASCII'.
	Possible values:
	- Unicode
	- UTF7
	- UTF8
	- ASCII
	- UTF32
	- BigEndianUnicode
	- Default
	- OEM

.PARAMETER ShowFile
	Specifies if you want to display the content of the generated temporary file.
	NOTE: The default .txt application will be used.
	
.PARAMETER RetriesRandomFileGeneration
	Specifies in case of generated filename already exists, how many retries will be done to get a non existing file name. The default is '10'.

.EXAMPLE
	$TempFile = Get-Process | Out-TempFile
	
	Description
	-----------
	This command will store the output of the Get-Process cmdmet to a temporary file. The generated file path will be stored to $TempFile variable.

.EXAMPLE
	$TempFile = Get-Process | Out-TempFile -RetriesRandomFileGeneration 1000 -ShowFile
	
	Description
	-----------
	This command will store the output of the Get-Process cmdmet to a temporary file. In case of the generated file name already exist, it will try up to 1000 times to generate a unique filename.
	After 1000 retries the script will stop and show an error. The generated file path will be stored to $TempFile variable. The content temporary file also will be displayed in the default txt
	application.

.EXAMPLE
	$TempFile = Get-Process | Select-object  "Id","ProcessName" | ConvertTo-Csv -NoTypeInformation | Out-TempFile -Encoding "Unicode" -Path "C:\TEMP"
	
	Description
	-----------
	This command will store the output of the Get-Process cmdmet, csv formatted to a temporary file using "Unicode" encofing. The generated file path will be stored to "C:\TEMP" directory.

.LINK
	http://blogs.technet.com/b/heyscriptingguy/archive/2011/04/15/the-2011-scripting-games-advanced-event-10-use-powershell-to-create-a-function-to-create-temp-files.aspx
#> 

Function Out-TempFile
{
	[cmdletbinding(
		DefaultParameterSetName = 'InputObject',
		ConfirmImpact = 'low'
	)]
	Param
	(
		[parameter(
		Mandatory=$true,
        ValueFromPipeline=$true)]
		[psobject[]]$InputObject,
		
	    [Parameter(
	    Mandatory = $False)]
		[string]$Path=$env:TEMP,
		
		[Parameter(Mandatory=$false)]
		[ValidateSet("Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode","Default","OEM")]
		$Encoding="Ascii",
		
		[Parameter(Mandatory=$false)]
		[switch]$WhatIf,
		
		[Parameter(Mandatory=$false)]
		[switch]$ShowFile,
		
		[Parameter(Mandatory=$false)]
		[int]$RetriesRandomFileGeneration=10
	)
	Begin
	{
		Write-Verbose "Start Out-Temp"
		
		Write-Verbose ("Testing if the path [{0}] accesible..." -f $Path)
		Write-Debug ""
		If (Test-Path -Path $Path)
		{
			Write-Verbose "Path is accessible."
			Try
			{
				#Generate a random file name. Ensure that the file doesn't exist.
				#If exist, a new one will be generated.
				$RandomFileTry=0
				do
				{
					#Set the temporary file name on the specified path.
					$LogFile=([System.IO.Path]::GetRandomFileName() + ".txt")
					Write-Verbose ("Generated random file name: {0}" -f $LogFile)
					Write-Debug ("Generated random file name: {0}" -f $LogFile)
					$LogFilePath=Join-Path -Path $Path -ChildPath $LogFile 
					$RandomFileTry++
				}
				While (((Test-Path $LogFilePath) -eq $true) -and ($RandomFileTry -lt $RetriesRandomFileGeneration))
				
				if ($RandomFileTry -eq $RetriesRandomFileGeneration)
				{
					Write-Error ("After {0} times, it's impossible to get a new temporary file on the specified path." -f $RetriesRandomFileGeneration)
					exit
				}
			}
			Catch
			{
				Write-Debug ("ERROR Generating the temporary file name!: [{0}]" -f $_)
				Write-Warning "Can't generate the temporary file!"
				exit
			}
		}
		else
		{
				Write-Error ("ERROR Can't access assigned path!: [{0}] . Script aborted." -f $Path)
				exit
		}
		#Define the collector object.
		$ToOutput=@()
		#Define a counter to count how many objects will be sent to the temporary file.
		$ObjectsNum=1
		

	}#Begin
	Process
	{
		if (!$WhatIf)
		{
			Write-Verbose ("{0}`t - Processing input..." -f $ObjectsNum)
			Write-Debug $_
			$ToOutput+=@($InputObject)
			$ObjectsNum++
		}
	}#Process
	End
	{
		if (!$WhatIf)
		{
			Try
			{
				Write-Verbose "Writting objects to the temporary file"
				Write-Debug "Writting objects to the temporary file"
				$ToOutput | Out-File -FilePath $LogFilePath -Encoding $Encoding
				
			}
			Catch
			{
				Write-Debug ("ERROR writting the file!: [{0}]" -f $_) 
				Write-Warning " Error writing the file!"
			}
		}
		else
		{
			Write-Host ("What if: Writting the input object to:`n[{0}]" -f $LogFilePath)
			Write-Host  "The file name path will be the same in every execution but not the file name,because it's a random generated file name."
		}
			
		if($ShowFile)
		{
			if ($WhatIf)
			{
				Write-Host "What if: Launching default txt application to display the generated file."
			}
			else
			{
				Write-Verbose "Launching default txt application to display the generated file."
				Write-Debug "Launching default txt application to display the generated file."
				. $LogFilePath
			}
		}
		
		Write-Verbose ("Returning Generated file path: [{0}]" -f $LogFilePath)
		return $LogFilePath
		Write-Verbose "End Out-Temp"
	}#End
}
Top

Comments:

4/24/2011 8:06 PM
Very good script..

One thing to consider is using SupportsShouldProcess to implement -whatif and -confirm