Extension for temporary files

When I did the post on creating temporary files http://msmvps.com/blogs/richardsiddaway/archive/2009/11/05/creating-temporary-files.aspx I said I’d modify it so the file would be created with a given extension.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
## asssume that want temp files in multiples of 1KB or empty
## renaming Get-ChildItem -Path c:\test\test2 | Rename-Item -NewName {$_.Name -replace "\....", ".txt"}
function New-TempFile {
param (
[string]$path = "C:\Test",
[int]$size = 1KB,
        [string]$ext = ""
)
if (!(Test-Path -Path $path)){throw "Invalid path"}
$file = [System.IO.Path]::GetRandomFileName()
    if ($ext -ne "") {
        if ($ext.StartsWith(".")){$ext = $ext.Remove(0,1)}
        $file = $file -replace "\....", ".$ext"
    }

if ($size -eq 0){
New-Item -Path $path -Name $file -ItemType 'File'
}
else {
$data = "*" * 128
$lines = [System.Math]::Ceiling(($size / 1kb) * 8)
for ($i=1; $i -le $lines; $i++){
Add-Content -Path $(Join-Path -Path $path -ChildPath $file) -Value $data
}
        Get-ChildItem -Path $path -Filter $file
}
}

 

It just involves adding another parameter $ext with a default empty string value.  If we give an extension

New-TempFile -size 2kb -ext "txt" -path "c:\test\test2"

Then we test to see if it starts with a .   and remove it.  We then replace the extension of the randomly generated filename using a regular expression match on the extension [ the regex is translated as 3 characters following a .  The \ is an escape character so . is read literally rather than as a wildcard]

Everything else is the same.  One other thing I might do is change the way data is put into the files.  For larger files its slow so I might do something different there.  This is one of great features of working with PowerShell like this – I can get a working script quickly and then refine it over time as I get chance to think about it.  Because I can work interactively at the prompt I can quickly test ideas before changing the script.

Published Wed, Nov 11 2009 19:52 by RichardSiddaway

Leave a Comment

(required) 
(required) 
(optional)
(required)