This is an expansion of my previous article about creating temporary files in PowerShell. What’s new here is I’ve wrapped the whole concept into a self-contained function complete with a proper parameter block and a (hopefully) adequate degree of error checking. This is a conceptual repeat of the previous article, but there a quite a few improvement and I am personally finding the function to be so useful that I’m loading into memory via my $profile script. Note: be aware that loading this function via the $profile script will cost you in terms of portability if you create a script that expects the function to be predefined.
Function: NewTempFile
The function is called “NewTempFile” and works as follows: You call NewTempFile passing three optional parameters (explained below) that will result in the creation of a temporary filename (based on your parameters and the current date/time). The function has the ability to create the containing folder(s) if they do not already exist and (as a precaution) will abort in the unlikely event that the generated filename already exists.
The resulting format is DirectoryPath\FilePrefix_YYYYMMDD-hhmmss-mmmm.FileType
Where:
YYYYMMDD = Year Month day (e.g. “20100830″) August 30, 2010
hhmmss = Hour Minute Second (e.g. “100548″) 10:05:48 AM
mmmm = Miliseconds (e.g. “446721″)
Example Temp File Name:
“c:\temp\MyTempFile_20100830-102205-2134.log”
You have complete control over the DirectoryPath, FilePrefix, and FileType components.
Step 1: Accept Parameters
The three optional Parameters can be specified by name or positionally qualified
<
function NewTempFile() { Param ( [parameter(Position=0)] [string] $folder="", [parameter(Position=1)] [string] $filePrefix="temp", [parameter(Position=2)] [string] $fileType="log" ) |
- $folder is the directory path to the location where you want to create your temporary file. If omitted, the file will be created in your current working directory
- $filePrefix is a string of your choosing to make the resulting file easy to recognize. If omitted, “temp” will be used.
- $fileType is a string of your choosing to be appended to the file. If omitted, “.log” will be appended. Note you do not include the period (“.”) when specifying the file type.
Step 2: Create the Folder
<
#create the folder (if needed) if it does not already exist if ($folder -ne "") { if (!(test-path $folder)) { write-host "creating new folder `"$folder`"..." -back black -fore yellow new-item $folder -type directory | out-null } if (!($folder.endswith("\"))) { $folder += "\" } } |
Not too much to explain here…
- If $folder is not defined, don’t worry about it, the temp file will be created in the current working directory
- If $folder is defined, test to see if it exist and if not, go ahead and create the directory. Note, the new-item cmdlet will actually create multiple levels of directories in a single call; if you want to specify “c:\level1\level2″ and neither directory exists, the single new-item call will create both directory levels.
- Finally, if the $folder specification ends with a path separator (“\”) find; if not, we append it
Step 3: Generate A Unique filename using the current date/time
<
#generate a unique file name (with path included) $x = get-date $TempFile=[string]::format("{0}_{1}{2:d2}{3:d2}-{4:d2}{5:d2}{6:d2}-{7:d4}.{8}", $filePrefix, $x.year,$x.month,$x.day,$x.hour,$x.minute,$x.second,$x.millisecond, $fileType) $TempFilePath=[string]::format("{0}{1}",$folder,$TempFile) |
Again, fairly straight forward – we’re just getting the current date/time using the get-date cmdlet and then using the [string]::format method to piece all of the filename components together
Step 4: Create the New Temporary File
#create the new file if (!(test-path $TempFilePath)) { new-item -path $TempFilePath -type file | out-null } else { throw "File `"$TempFilePath`" Already Exists!" } return $TempFilePath |
- Here we will do a quick check using the test-path cmdlet to make sure that our new temp file does not already exist. Since we’re creating the filename using a timestamp specification down to the milisecond, it’s unlikely to have an error here, but we’ll check anyway and abort with an exception if needed.
- Next we (finally) create the new temporary file
- Lastly, we will return the complete Temporary file path to the calling program so it can be used to write output
If you’ve read this far, I suppose chances are pretty good that you might want to use this function so here it is, ready for download or cut-and-paste from this BLOG to your computer. Once you have downloaded the function, call it like so:
$x = NewTempFile write-host $x |
As always, Enjoy and come back and visit us soon!
Complete “NewTempFile” function:
function NewTempFile() { Param ( [parameter(Position=0)] [string] $folder="", [parameter(Position=1)] [string] $filePrefix="temp", [parameter(Position=2)] [string] $fileType="log" ) #create the folder (if needed) if it does not already exist if ($folder -ne "") { if (!(test-path $folder)) { write-host "creating new folder `"$folder`"..." -back black -fore yellow new-item $folder -type directory | out-null } if (!($folder.endswith("\"))) { $folder += "\" } } #generate a unique file name (with path included) $x = get-date $TempFile=[string]::format("{0}_{1}{2:d2}{3:d2}-{4:d2}{5:d2}{6:d2}-{7:d4}.{8}", $filePrefix, $x.year,$x.month,$x.day,$x.hour,$x.minute,$x.second,$x.millisecond, $fileType) $TempFilePath=[string]::format("{0}{1}",$folder,$TempFile) #create the new file if (!(test-path $TempFilePath)) { new-item -path $TempFilePath -type file | out-null } else { throw "File `"$TempFilePath`" Already Exists!" } return $TempFilePath } |
Recent Comments