Working in and with Temporary Folders
Sometimes, we have to create a (totally random named) temporary folder, do some stuff in it and then delete everything. Here’s the way
# Let's generate a random name for our temporary folder $TempDir = [System.Guid]::NewGuid().ToString() # Now we can create our temporary folder New-Item -Type Directory -Name $TempDir # Let's go in our newly created temporary folder Set-Location $TempDir <do what you have to do in the Temp Directory...> # Let's remove everything we put in our temporary folder Remove-Item *.* -Force # Let's go one level up Set-Location .. # And delete our temporary folder Remove-Item $TempDir
Wanna do it in a “clean” temporary structure, let’s do it in $env:temp
# Where are we? $location = $pwd.Path # Let's generate a random name for our temporary folder $TempDir = [System.Guid]::NewGuid().ToString() # Let's go in the temp environment variable Set-Location $env:temp # Now we can create our temporary folder New-Item -Type Directory -Name $TempDir # Let's go in our newly created temporary folder Set-Location $TempDir <do what you have to do in the Temp Directory...> # Let's remove everything we put in our temporary folder Remove-Item *.* -Force # Let's go one level up Set-Location .. # And delete our temporary folder Remove-Item $TempDir # Let's go back to our initial location Set-Location $location
Another way to do it is decribed (the part that creates the temporary folder only) here: http://joelangley.blogspot.fr/2009/06/temp-directory-in-powershell.html