PowerShell: Temporary Folders

Scriptimus_PowerShell_Banner

I was looking through some old code and came across an alternate way to create a temporary folder using PowerShell(or .NET if you want to be picky).

So, I needed to create a temporary folder and constructed this line of code. It created a temporary folder path that I could use to build files in one of my DSC Testlab projects.

([System.IO.Path]::GetTempPath()+'~'+([System.IO.Path]::GetRandomFileName())).Split('.')[0]

Temp_Folders_1

Here’s how it works. First, I use GetTempPath to return the current temp folder path.

[System.IO.Path]::GetTempPath()

Temp_Folders_2

Then add a tilde ( ‘~’ ) as a prefix as this is a universally recognised method of prefixing a temp file or folder name.

Next I generate a random folder using the GetRandomFileName method.

[System.IO.Path]::GetRandomFileName()

Temp_Folders_3

Now I didn’t need the file extension at the end so I removed it by using the split method to split it into 2 objects returning only the first part.

[System.IO.Path]::GetRandomFileName().Split('.')[0]

Temp_Folders_4

This worked great and I later learned that I could do something similar by using GetTempFileName which would be less code.

[System.IO.Path]::GetTempFileName()

Temp_Folders_5

Sweet! Next do the split trick again to use the string as a folder path.

[System.IO.Path]::GetTempFileName().Split('.')[0]

Temp_Folders_6

The issue with this though is that the GetTempFileName method actually generates a zero byte file and returns the string. This is very useful in some scenarios but not for my task of just creating an empty folder.

Temp_Folders_7

After a bit of research I decided to stay with my first option.

 

 

Advertisements

About Andrew Barnes

A Scripting and Deployment Specialist.
This entry was posted in Scripting, Uncategorized and tagged , , . Bookmark the permalink.

2 Responses to PowerShell: Temporary Folders

  1. How about using GUID for random folder name…

    New-item “$env:temp\$([GUID]::NewGuid())” -ItemType Directory

    Rg./Irwin

    Like

    • Yeah, good point. I suppose all we’re doing here is generating a random and unique string. So I suppose you could also use Get-date -Format ddMMyyhhmmss for a unique string, Get-random or even the random password generator I posted earlier.

      Liked by 1 person

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