Remove everything in temp folder, delete temp, and make a new temp
-
22-06-2021 - |
Frage
I have a script that I'm working on that is intended to remove the temp folder (in C Disk), delete everything in temp, and then create a new temp folder. I have the script already created to delete everything, however I'm unsure of how you go about creating a new temp folder with Powershell. Was wondering if anyone might know how to create the new temp folder in Powershell.
#remove all temporary files
if($serverVersion.name -like "*2003*"){
$dir = "\\$server" + '\C$\temp'
}
elseif($serverVersion.name -like "*2008*"){
$dir = "\\$server" + '\C$\Windows\Temp'
}
$tempArray = @()
foreach ($item in get-childitem -path $dir){
if ($item.name -like "*.tmp"){
$tempArray = $tempArray + $item
}
}
for ($i = 0; $i -le $tempArray.length; $i++){
$removal = $dir + "\" + $tempArray[$i]
remove-item $removal -force -recurse
}
Am I correctly deleting the temp folder as well and, what would I have to do to create a new temp folder?
EDIT: I've updated my code based on what people have suggested, was wondering if this would have the desired effects and if there's a way to cut this down even further:
if($serverVersion.name -like "*2003*"){
$dir = "\\$server" + '\C$\temp'
remove-item $dir -force -recurse
new-item -path "\\$server" + '\C$\Windows\temp' -Type Directory
}
elseif($serverVersion.name -like "*2008*"){
$dir = "\\$server" + '\C$\Windows\Temp'
remove-item $dir -force -recurse
New-Item -Path "\\$server" + '\C$\Windows\Temp' -Type Directory
}
Lösung
Use the New-Item
cmdlet to create the folder:
New-Item -Path "\\$server\admin$\Temp" -Type Directory
You can also use the 'md' alias (points to the mkdir function):
md "\\$server\admin$\Temp" -Force
UPDATE:
Here's what I would do: remove the directory. Check the $? variable (returns $true if the last command succeeded), if the command didn't completed successfully - create the Temp folder, otherwise there must have been an error and the Temp dir still exist.
Remove-Item -Path "\\$server\admin$\Temp" -Force -Recurse
if($?)
{
New-Item -Path "\\$server\admin$\Temp" -Type Directory
}
p.s. You could also add the Force switch to New-Item (or 'md') and create the folder regardless of the result of the previous command.
Andere Tipps
Why don't you simply remove temp folder with a recursive remove-item
# Remove recursively
Remove-Item -Path "\\$server\admin$\Temp" -Force -Recurse
# Create another one
New-Item -Path "\\$server\admin$\Temp" -Type Directory