Temporary file-names

Overview

If you ever have the need to create temporary file-names relating to your temporary folder, the methods GetRandomFileName and GetTempPath from the class System.IO.Path can be used. I say relating to because the code doesn’t actually create the file. That will have to be another step if that’s what you require.

Code

The PowerShell way to achieve this is as follows.

$tempPath = [System.IO.Path]::GetTempPath()
$tempFileName = [System.IO.Path]::GetRandomFileName()
$tempResult = Join-Path $tempPath $tempFileName

The method GetTempPath, returns the path of the current user’s temporary folder. This gives me:

C:\Users\w7\AppData\Local\Temp\

The method GetRandomFileName returns a cryptographically strong, random string that can be used as either a folder name or a file name. This will return (for example):

an1ldcxk.iom

bearing in mind that a different file name will be returned each time you execute the method.

To make use of all this, we can join the above information together with the Join-Path CmdLet. In the examples used, the variable tempResult, gets assigned the value:

C:\Users\w7\AppData\Local\Temp\an1ldcxk.iom

Advertisements
This entry was posted in powershell and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s