header image

Creating Temporary files

Posted by: | November 5, 2009 | No Comment |

One thing I need to do when testing file system scripts is generate a bunch of temporary files for experimenting with.  In the past I have just copied in whatever I could find to use as test data.  It is possible to easily generate test data of this sort using the New-TempFile function below.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
## asssume that want temp files in multiples of 1KB or empty
function New-TempFile {
param (
[string]$path = "C:\Test",
[int]$size = 1KB
)
if (!(Test-Path -Path $path)){throw "Invalid path"}
$file = [System.IO.Path]::GetRandomFileName()

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
}
}

 

The function takes two arguments – a path and a file size. My default values are given but they can be easily changed to suit you system.

After checking that the path exists I generate a random file name using GetRandomFile().  We could use GetTempFileName() but that creates an empty file in the temporary folder which isn’t quite what I want.

If the size is zero an empty file is created on the given path. Otherwise if size is supplied e.g.

New-TempFile -size 5kb

then a number of 128byte lines are written into the file.  If larger files are being routinely created increase the size of the string to 512 bytes – or put a test on say 100kb size and use the bigger string in that case.

Add-Content is used to write the data into the file.

One enhancement is to allow the setting of the file extension.

Technorati Tags: ,,
under: PowerShell original