Average Rating:

3.50 by 2 users.

24 Downloads, 56 Views

2 Comment(s)


By: Nuno Mota 20 Apr 2011 11:28 AM UTC in the category: Advanced Event 10


- The function accepts piped content;
- The function returns the path to the temporary file IF the user does not use the -WhatIf parameter;
- The files are created in the TEMP_20110415.txt format, for example, and in C:\Windows\Temp by default. If not possible, then in C:\Temp;
- If the user uses the -OpenFile switch, the temporary file will be opened in Notepad at the end of the script;
- The user can use the -Encoding parameter to specify ASCII or Unicode to use when writing to the script;
- The function also fully supports the WhatTf, Debug, and Verbose parameters.
# Script:	AdvancedEvent10.ps1
# Purpose:	Script for the 2011 Scripting Games: Advanced Event 10 - Use PowerShell to Create a Function to Create Temp Files
# Author:	Nuno Mota
# Date:		April 2011

Function writeToNewTempFile
	    Use PowerShell to Create a Function to Create Temp Files
		This script accepts piped input and writes it to a temporary file in C:\Windows\Temp
		If this folder cannot be used, the script will create and use C:\Temp instead.
		If the user does not use the -WhaIt parameter, the function will return the path to the temporary file.
		To use this function, please run: C:\PS> . ./AdvancedEvent10.ps1
		                                  C:\PS> "Scripting Games" | writeToNewTempFile

		This parameters specifies text to be written to the temporary file. It can be used together with text from the pipe.
	.PARAMETER Encoding
		This parameter allows the user to specify ASCII or UNICODE to be used when writting to the file. If not used, UNICODE will be used by default.

		When used, this parameter will make Notepad open with the file that has just been created by the script.
		This if the user doesn't use the -WhatIf parameter in which case there is no file to open.
	    C:\PS> "Scripting Games", "RULEZ!!!" | writeToNewTempFile
	This command will add the text "Scripting Games" and "RULEZ!!!" (in different lines) to a temporary file in C:\Windows\Temp.

	    C:\PS> "Scripting Games" | writeToNewTempFile -Text "RULEZ!!!" -Encoding ASCII -OpenFile
	This command will add the text "Scripting Games" and "RULEZ!!!" (in different lines) to a temporary file in C:\Windows\Temp using ASCII encoding.
	When finished, Notepad will be opened

		[Parameter(Position=0, Mandatory=$False, ValueFromPipeline=$True)] 
		[String] $Text,

		[Parameter(Position=1, Mandatory=$False)]
		[ValidateSet("ASCII", "Unicode", "Default")]
		[String] $Encoding = "Default",

		[Parameter(Position=2, Mandatory=$False)] 
		[Switch] $OpenFile,
		[Parameter(Position=3, Mandatory=$False)] 
		[Switch] $WhatIf = $False

	Begin {
		# Check if the user used any behavior variable and, if so, update its preference variable
		If ($Debug)		{ $DebugPreference		= "Continue" }
		If ($Verbose)	{ $VerbosePreference	= "Continue" }
		If ($WhatIf)	{ $WhatIfPreference		= $True }

		# Build the filename in the format: TEMP_20110415.txt
		$strFileName = "TEMP_$(Get-Date -Format 'yyyyMMdd').txt"
		# Let's try to create the file in the Windows' Temp folder
		If (Test-Path "C:\WINDOWS\Temp")
			$strFolderPath = "C:\WINDOWS\Temp"
			# If we can't, lets create a Temp folder in the root of the C: drive
			If (!(Test-Path "C:\Temp"))
				Try {
					New-Item -Path "C:\Temp" -ItemType Directory -Force -Verbose:$VerbosePreference -WhatIf:$WhatIfPreference | Out-Null
				} Catch {
					Write-Debug "Could not create ""C:\Temp"" directory."
			$strFolderPath = "C:\Temp"

		# Join the path and the file name together to form the full path
		$strFilePath = Join-Path $strFolderPath $strFileName -Verbose:$VerbosePreference

		# Check if the file already exists. If yes, append its name with an incrementing number
		# This way, no matter how many times this function is used, a new temp file is always created
		If (Test-Path $strFilePath)
			# If TEMP_20110415.txt already exists, create TEMP_20110414_1.txt
			[Int] $intCount = 1
			$strFilePath = $strFilePath.Replace(".txt", "_$($intCount + 1).txt")

			While (Test-Path $strFilePath)
				# If TEMP_20110415_1.txt already exists, create TEMP_20110415_2.txt and so on
				$strFilePath = $strFilePath.Replace("_$($intCount)", "_$($intCount + 1)")

		Try {
			New-Item -Path $strFilePath -ItemType File -Force -Verbose:$VerbosePreference -WhatIf:$WhatIfPreference | Out-Null
		} Catch {
			Write-Debug "Could not create ""$($strFilePath)"" file."

	# Write the text to the temporary file we just created
	Process {
		$Text | Out-File $strFilePath -Encoding $Encoding -Append -Verbose:$VerbosePreference -WhatIf:$WhatIfPreference

	End {
		If (!$WhatIf)
			# Open Notepad with the new file if the user did not use the -WhatIf parameter (in which case no file was created)
			# and if the user used the -OpenFile parameter
			If ($OpenFile) { Invoke-expression "notepad.exe $strFilePath" }
			Return $strFilePath


4/24/2011 8:23 PM
Good script that does what it is supposed to.
I would consider using environment variables to "locate" temp folders or use a "built in" function like [System.IO.Path]::GetTempFileName() which will give you a unique filename in the temp folder .
Consider using SupportsShouldProcess for whatif as well...
4/25/2011 12:05 AM
Hi Claus,
Thank you very much for your feedback. Excellent tips, thank you very much! :)