Delete contents of temp folder - powershell

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.

Related

Copy all latest files from folders/sub to the same name folders/sub in powershell

I am trying to copy the latest file from every folder/sub-folder into a same file structure on a different drive.
Latest file from source copied to the same name corresponding destination.
The destination folder hierarchy already exists & cannot be copied over or recreated. This & other versions are not behaving. Can anyone help?
$sourceDir = 'test F Drive\Shares\SSRSFileExtract\'
$destDir = 'test X Drive\SSRSFileExtract\'
$date = Get-Date
$list = Get-ChildItem -Path $sourceDir | Sort-Object -Property LastWriteTime -Descending | Select-Object -First 1
foreach ($item in $list)
{
Copy-Item -Verbose -LiteralPath $item.FullName -Destination $destDir -Force |
Get-Acl -Path $item.FullName | Set-Acl -Path $destDir\$(Split-Path -Path $item.FullName -Leaf)
}
Get-ChildItem –Path $destDir -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-5))} | Remove-Item -Verbose -Recurse -Force
I found a solution for this which copies/moves all the files from all sub folders in to all corresponding sub folders:
Powershell: Move all files from folders and subfolders into single folder
The way your code retrieves the list of files will only return one single object because of Select-Object -First 1. Also, because you don't specify the -File switch, Get-ChildItem will also return DirectoryInfo objects, not just FileInfo objects..
What you could do is get an array of FileInfo objects recursively from the source folder and group them by the DirectoryName property
Then loop over these groups of files and from each of these groups, select the most recent file and copy that over to the destination folder.
Try:
$sourceDir = 'F:\Shares\SSRSFileExtract'
$destDir = 'X:\SSRSFileExtract'
Get-ChildItem -Path $sourceDir -File -Recurse | Group-Object DirectoryName | ForEach-Object {
# the $_ automatic variable represents one group at a time inside the loop
$newestFile = $_.Group | Sort-Object -Property LastWriteTime -Descending | Select-Object -First 1
# construct the target sub directory
# you could also use $_.Name (the name of this group) instead of $newestFile.DirectoryName here, because
# we grouped on that DirectoryName file property.
$targetDir = Join-Path -Path $destDir -ChildPath $newestFile.DirectoryName.Substring($sourceDir.Length)
# if you're not sure the targetpath exists, uncomment the next line to have it created first
# if (!(Test-Path -Path $targetDir -PathType Container)) { $null = New-Item -Path $target -ItemType Directory }
# copy the file
$newestFile | Copy-Item -Destination $targetDir -Force -Verbose
# copy the file's ACL
$targetFile = Join-Path -Path $targetDir -ChildPath $newestFile.Name
$newestFile | Get-Acl | Set-Acl -Path $targetFile
}
Apparently you would also like to clean up older files in the destination folder
Get-ChildItem –Path $destDir -File -Recurse |
Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-5).Date} |
Remove-Item -Verbose -Recurse -Force
Be aware that the final code to remove older files could potentially remove all files from a subfolder if all happen to be older than 5 days..

Duplicate file name as folder, insert file

I am trying to use Powershell to
scan folder D://Mediafolder for names of media files
create a folder for each media file scanned, with same name
insert each media file in to matching folder name.
I can find no documentation or thread of this, and I am more fluent in Linux than Windows. I've tried many times to piece this together, but to no avail.
Hope this will help :)
This will create a folder for each file with the same name, so if you have a file called xyz.txt, it will create a folder called xyz and move the file to this folder.
$path = "D:\MediaFolder"
$items = Get-ChildItem $path
Foreach ($item in $items)
{
$folderName = $item.name.Split('.')[0]
New-Item "$path\$folderName" -ItemType Directory
Move-Item -Path "$path\$item" -Destination "$path\$foldername"
}
File Sorting based on extension should do the job:
$folder_path = read-host "Enter the folder path without space"
$file = gci $folder_path -Recurse | ? {-not $_.psiscontainer}
$file | group -property extension | % {if(!(test-path(join-path $folder_path -child $_.name.replace('.','')))){new-item -type directory $(join-path $folder_path -child $_.name.replace('.','')).toupper()}}
$file | % { move-item $_.fullname -destination $(join-path $folder_path -child $_.extension.replace(".",""))}
$a = Get-ChildItem $folder_path -recurse | Where-Object {$_.PSIsContainer -eq $True}
$a | Where-Object {$_.GetFiles().Count -eq 0} | Remove-Item -Force
This will iterate over the files in the media_dir and move those with the extensions in media_types to a folder with the same basename. When you are satisfied that the files will be moved to the correct directory, remove the -WhatIf from the Move-Item statement.
PS C:\src\t> type .\ms.ps1
$media_dir = 'C:\src\t\media'
$new_dir = 'C:\src\t\newmedia'
$media_types = #('.mp3', '.mp4', '.jpeg')
Get-ChildItem -Path $media_dir |
ForEach-Object {
$base_name = $_.BaseName
if ($media_types -contains $_.Extension) {
if (-not (Test-Path $new_dir\$base_name)) {
New-Item -Path $new_dir\$base_name -ItemType Directory | Out-Null
}
Move-Item $_.FullName $new_dir\$base_name -WhatIf
}
}

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
}

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

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

Copy a file including it's relative path

I need to copy a large number of files to a backup folder but I want to maintain their relative paths. I only need specific files; i.e.
C:\scripts\folder\File.ext1
C:\scripts\folder2\file2.ext2
C:\scripts\file3.ext1
But I only need to copy the ext1 files like so:
C:\backup\folder\File.ext1.bak
C:\backup\file3.ext1.bak
The source paths are of multiple depths.
This is what I have to copy the files:
$files = gci -path C:\scripts\ -recurse -include *.ext1
$files | % { Copy-Item $_ "$($_).bak"; move-item $_ -destination C:\backup\ }
This just dumps all the files into C:\backup\ and does not appear to get any of the paths. Not sure how that part would be done.
Something like this could work:
gci -path C:\scripts\ -recurse -include *.ext1 |
% { Copy-Item $_.FullName "$($_.FullName).bak"
move-item $_.FullName -destination ($_.FullName -replace 'C:\\scripts\\','C:\backup\') }
It is not clever, but it's quick & dirty and works without a lot of effort.
get-childitem returns absolute paths, but you can make them relative to the current working directory as follows:
resolve-path -relative
So to copy a filtered set of files from the current directory recursively to a destination directory:
$dest = "c:\dest"
$filter = "*.txt"
get-childitem -recurse -include $filter | `
where-object { !$_.PSIsContainer } | `
resolve-path -relative | `
% { $destFile = join-path $dest $_; new-item -type f $destFile -force | out-null; copy-item $_ $destFile; get-item $destfile; }
new-item is needed to create the parent directories
get-item provides a display of all the new files it created
Of course robocopy does all this, but there will be times when you want to do more special filtering or filename mangling...
Use robocopy.
robocopy c:\scripts c:\backup *.ext1 /s
Oops. I failed to notice you wanted to add the .bak extension too. I still think it is a good idea to use robocopy to copy the files then:
dir c:\backup -recurse -include *.ext1 | % { ren $_ "$_.bak" }
You can try this
Clear-Host
$from = "'C:\scripts\"
$to = "'C:\backup\"
$inc = #('*.ext1', '*.extx')
$files = get-childItem -path $from -include $inc -Recurse
$files | % {$dest = (Join-Path $to $($_.FullName+".bak").SubString($from.length)); $dum = New-Item -ItemType file $dest -Force; Copy-Item -Path $_ -Destination $dest -Recurse -Force }
the new-item is there in order to force path creation.
Jean Paul