PowerShell: Temporary Folders


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.



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



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.



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.



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



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



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.


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




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



    • 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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s