Remove everything in temp folder, delete temp, and make a new temp - powershell

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
}

Use the New-Itemcmdlet 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.

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

Related

copy files from folder and then delete some files with an exception

I have folder called Logfolder in C.
C:\LogFolder
it has multiple logs with name as follows
errorLogs.log
errorLogs.log.1
errorLogs.log.2
errorLogs.log.3
Transmitlogs.log
Transmitlogs.log.1
Transmitlogs.log.2
Transmitlogs.log.3
Transmitlogs.log.4
Transmitlogs.log.5
Receivelogs.log
Receivelogs.log.1
Receivelogs.log.2
Receivelogs.log.3
Receivelogs.log.4
Dataexchange.log
Dataexchange.log.1
and many other with the different name but with same extension like .log, .log.1 and so on.
I am interested in only above mention logs.
my goal is to copy this logs starting from log.1 upto log.10 or 20 all which exist and than
delete the original file with an exception .log and .log.1.
I have achieved following until now.
$logLocation = "C:LogFolder"
$tempLocation = "C:\Temp\Logs\"
$LogfileName = "errorLogs.log.", "Transmitlogs.log.","Receivelogs.log.","Dataexchange.log."
foreach ($element in $LogfileName)
{
$NewLogFileName = -join($element,"*")
Copy-Item -Path "$logLocation\$NewLogFileName" -Destination $tempLocation
}
I am able to copy all logs starting from .log.1 and all other which exist.
my problem is how can i delete those logs from original folder without deleting .log and .log.1
I have tried the following but not working.
foreach ($element in $LogfileName)
{
$deleteLogFileName = -join($element,"*")
Remove-Item –path "$logLocation\$deleteLogFileName" -exclude *.log, *.log.1
}
You can do that by selectively copy only file *.log.1 to the destination folder and move the others. That would save you removing files from the source location afterwards.
The thing that matters here most is to get a list of files that
have a numeric extension
have a basename like 'errorLogs.log', 'Transmitlogs.log', 'Receivelogs.log' or 'Dataexchange.log'
Try
$logLocation = "C:\LogFolder"
$tempLocation = "C:\Temp\Logs"
# if the destination folder does not exist yet, creatre it first
if (!(Test-Path -Path $tempLocation -PathType Container)) {
$null = New-Item -Path $tempLocation -ItemType Directory
}
# get an array of objects of the files where the extension ends in a numeric value
# and where the basename is either 'errorLogs.log', 'Transmitlogs.log', 'Receivelogs.log'
# or 'Dataexchange.log'.
$files = Get-ChildItem -Path $logLocation -Filter '*.log*' -File |
Where-Object {$_.Name -match '^(errorLogs|Transmitlogs|Receivelogs|Dataexchange)\.log\.\d+$' } |
Select-Object FullName, #{Name = 'Number'; Expression = {[int]($_.Name.Split(".")[-1])}}
foreach ($file in $files ) {
if ($file.Number -eq 1) {
# this file should be copied
Copy-Item -Path $file.FullName -Destination $tempLocation -Force
}
else {
# the others are to be moved
Move-Item -Path $file.FullName -Destination $tempLocation -Force
}
}

Create Subfolders using Powershell

Ok, looking for some assistance with Powershell. I need to create a subfolder with the same name in about 200 folders in a directory. So far I have this:
$folder = NewFolderName
new-item -type directory -path \\servername\directory\directory\$folder -Force
Will this work to create the single folder in all 200 folders?
Try the following code snippet:
$parent = '\\servername\directory'
$folder = 'NewFolderName'
Get-ChildItem -Path $parent -Directory |
ForEach-Object {
New-Item -WhatIf -Type Directory -Path (
Join-Path -Path $_.FullName -ChildPath $folder) -Force
}
Remove the risk mitigation parameter -WhatIf no sooner than debugged…

Move files into alphabetically named folders

Just wondering if it's possible to have a script move film files to a specific folder based on the alphabet?
Eg Scream 4 would get moved to e:\movies\s\
Avatar would get moved to e:\movies\a\
I start a script that looks like this :
But the result is not good!The script try to create a directory with files name...
$a = new-object -comobject wscript.shell
$b = Get-Location
foreach($file in (dir $b -file -recurse)) {
New-Item -Path $b -Name (Split-Path $file.fullname -Leaf).Replace($file.extension,"") -ItemType Directory -Confirm
Move-Item -Path $file.fullname -Destination "$b\$((Split-Path $file.fullname -Leaf).Replace($file.Extension,''))" -Confirm
}
An idea ?
Many thanks!
Kreg
Destination folders must exist before you run the command:
dir $b -file -recurse | Move-Item -Destination {"e:\movies\$($_.Name[0])"}
This will create the folders at run time:
dir $b -File -Recurse | foreach{
$folder = Join-Path e:\movies $_.Name[0]
md $folder -force | Out-Null
$_ | Move-Item -Destination $folder
}

Delete contents of temp folder

I've got the following code snippet which currently removes everything in my temp directory and re-adds a new temp directory.
if($serverVersion.name -like "*2003*"){
$dir = "\\$server" + '\C$\WINDOWS\Temp\*'
remove-item $dir -force -recurse
if($?){new-item -path "\\$server\admin$\Temp" -Type Directory}
}
elseif($serverVersion.name -like "*2008*"){
$dir = "\\$server" + '\C$\Windows\Temp\*'
remove-item $dir -force -recurse
if($?){New-Item -Path "\\$server\admin$\Temp" -Type Directory}
}
I'm trying to slightly alter the code to where it will no longer delete the temp directory and instead simply remove all of the contents inside of temp. I added \* at the end of my $dir variable so that it tries to get all of the items inside of temp rather than deleting Temp itself. When I run this however I'm not deleting anything. What is wrong with my code?
This works for me, so long as you meet the pre-reqs and have full control over all files/folders under Temp
# Prerequisites
# Must have the PowerShell ActiveDirectory Module installed
# Must be an admin on the target servers
#
# however if you have no permissions to some folders inside the Temp,
# then you would need to take ownship first.
#
$Server = "server Name"
$dir = "\\$Server\admin$\Temp\*"
$OS = (Get-ADComputer $Server -Properties operatingsystem).operatingSystem
IF (($os -like "*2003*") -or ($os -like "*2008*"))
{
remove-item $dir -Recurse -force
}
According to the PowerShell help file for remove-item, the -recurse parameter is faulty. It recommends that you get-childitem and pipe to remove-item. See example from the help file below.
-------------------------- EXAMPLE 4 --------------------------
C:\PS>get-childitem * -include *.csv -recurse | remove-item
Figured out how to do this and figure it may be useful for someone in the future.
if($serverVersion.name -like "*2003*"){
$dir = "\\$server" + '\C$\WINDOWS\Temp'
Get-ChildItem -path $dir -Recurse | %{Remove-Item -Path $_.FullName -Force}
if($?){new-item -path "\\$server\admin$\Temp" -Type Directory}
}
elseif($serverVersion.name -like "*2008*"){
$dir = "\\$server" + '\C$\Windows\Temp'
Get-ChildItem -path $dir -Recurse | %{Remove-Item -Path $_.FullName -Force}
write-host "success?"
if($?){New-Item -Path "\\$server\admin$\Temp" -Type Directory}
}
Using get-childitem it will look at everything inside of Temp without deleting Temp itself.

Powershell - Copying to a new folder

I am cleaning up some log files and trying to copy it to the new folder that gets created here.
but it fails in the line:
$newpath = join-path $f.directoryname\Cleaned $($f.basename + "_new" + $f.extension)
if I remove the "\Cleaned" part in that line, it works fine. but it copies the cleaned file on the same folder, which is not good.
I am not sure if the way I pass that new folder with the directory name is wrong. How do I do it right?
Function IIS-CleanUp1($path,$file)
{
$f = get-item $path\$file1
$newpath = join-path $f.directoryname\Cleaned $($f.basename + "_new" + $f.extension)
Get-Content $f | ? { $_ -match $control -and $_ -notmatch '^\#'} | Out-File $newpath
}
Function Files($path)
{
$allfiles = Get-ChildItem($path) -name
New-Item -ItemType directory -Path $path\Cleaned
foreach ($file1 in $allfiles)
{
IIS-CleanUp1($path,$file)
}
}
$path1 = "C:\Temp\IIS_CCHECK_AUG\IIS_CCHECK_AUG_202"
Files $path1
Q2:
I like to delete the directory "Cleaned", if it is already there, just above this line.
New-Item -ItemType directory -Path $path\Cleaned
when I try the following it does not work.
Remove-Item $path\Cleaned -force
Any ideas.
Thanks again.
-T
I think you need to have two parameters to join-path. Like join-path C:\ users (note the space). So put every extra path as a separate argument.
You need to fix the first path by adding quotes and get the inside evaluated to add \Cleaned:
$newpath = join-path "$($f.directoryname)\Cleaned" $($f.basename + "_new" + $f.extension)