Move folders if bigger than 2GB - powershell

I have tried to modify unsuccessfully another script that list correctly folders bigger than 2GB so that it moves them
(I only changed the row $fso = New-Object -COM 'Scripting.FileSystemObject') :
$threshold = 2GB
$fso = Move-Item -path -Destination "C:\Dest\"
Get-ChildItem 'C:\Source\' -Recurse -Directory | Where-Object {
$fso.GetFolder($_.FullName).Size -gt $threshold
}

I've finally found a solution (adapted from https://community.spiceworks.com/topic/2468783-ps-script-to-find-folder-1gb-and-move-to-another-folder) ! :
Get-ChildItem -Path 'C:\Source' -Directory | ForEach-Object {
$Folder = Get-ChildItem -Path $_.FullName -File -Recurse
$FolderSize = $Folder | Measure-Object -Sum Length
if ($FolderSize.Sum -gt 2GB) {
Write-Information -MessageData "$_ is larger than 2GB. Size is $FolderSize" -InformationAction Continue
Move-Item -Path $_.FullName -Destination 'C:\dest'
}
}

Related

How can I get Powershell to generate logs after moving files?

Hi this is the first time I create a program using powershell, I created a powershell script to move old files that are not in use to a NAS, the code works as what I want, but I need a Log.txt file for find out what files have been moved. can someone please help me?
$Date = Get-Date -UFormat %d-%m-%Y
$Source = 'C:\Source\'
$Temp = 'C:\Backup-Temp\'
$Nas = 'D:\Destination\'
$Ext = "*.zip","*.rar"
$SetTime = '-5'
New-Item -Path $Temp -Name "Backup-$Date" -ItemType "directory"
Foreach ($Ext in $Ext) {
get-childitem -Path "$Source" -Recurse |
Where-object {$_.LastWriteTime -lt (get-date).AddDays($SetTime) -and $_.name -like "$Ext"} |
Move-item -destination "$Temp\Backup-$Date" |
Compress-Archive -Path "$Temp\Backup-$Date" -DestinationPath "$Nas\Backup-$date.Zip"
}
$Date = Get-Date -UFormat %d-%m-%Y
$Source = 'C:\Source\'
$Temp = 'C:\Backup-Temp\'
$Nas = 'D:\Destination\'
$Ext = "*.zip","*.rar"
$SetTime = '-5'
$LogFileFullName = 'c:\tmp\log.txt'
function Write-Log([string]$msg){
Out-File -FilePath $LogFileFullName -InputObject "$([DateTime]::Now): $msg" -Append
}
New-Item -Path $Temp -Name "Backup-$Date" -ItemType "directory"
Foreach ($Ext in $Ext) {
get-childitem -Path "$Source" -Recurse |
Where-object {$_.LastWriteTime -lt (get-date).AddDays($SetTime) -and $_.name -like "$Ext"} |
ForEach-Object {
Move-item $_.FullName -destination "$Temp\Backup-$Date" |
Compress-Archive -Path "$Temp\Backup-$Date" -DestinationPath "$Nas\Backup-$date.Zip"
Write-Log $_.FullName
}
}
You could just add the following to your chain of piped commands:
Add-Content $logfile "$_.name`n"
where $logfile is set to a static filename prior.
I may be old-fashioned, but having so many commands in one chain is prone to failure. It would be more resilient to break-up the chain so that you can include some error checking along the way.
A better but less desirable option would be to put your chain within a try/catch block.
Best of luck.

Deleting files with Powershell recursively

I got somehow a weird issue, I am trying to use a process to automate the deletion of files from a folder and also child folders, I am trying to delete only files older than 7 days.
My code works but it deletes files that are under 7 days when going recursively into child items. . .anyone could lend a hand here? I just need to delete in each folder/sub-folder the files older than 7 days.
Param (
[string]$Source = "C:\Users\Loredanes\Downloads\",
[string]$Days = "1"
)
$Files = Get-ChildItem $Source -Recurse | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt (get-date).addminutes(-$($Days)) }
$Files | Remove-Item -Force
if ($Files.count -gt 0)
{
$Folders = #()
ForEach ($Folder in (Get-ChildItem -Path $Source -Recurse -Directory))
{
$Folders += New-Object PSObject -Property #{
Object = $Folder
Depth = ($Folder.FullName.Split("\")).Count
}
}
$Folders = $Folders | Sort Depth -Descending
ForEach ($Folder in $Folders)
{
If ($Folder.Object.GetFileSystemInfos().Count -eq 0)
{
Write-Host "Removing Folder: $($Folder)"
Remove-Item -Path $Folder.Object.FullName -Force
}
}
}
else
{
Write-Host "No Empty folders found after removing files older than $($Days) days."
}
This should do what you want:
$source = 'D:\Test'
$days = 7
# Remove Files
Get-ChildItem $Source -Recurse | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt (get-date).AddDays(-$($days)) } | % { Remove-Item -Path $_.FullName -Force }
# Remove empty directories
Get-ChildItem $source -Recurse | Where-Object { $_.PSIsContainer -and $_.GetFiles("*.*").Count -le 0 } | % { Remove-Item -Path $_.FullName -Force }

Batch Replace-Name & Move-item

I got a script:
$CopySource = "C:\Source\Qlikview Storage\PrivateData\Gemensamma\Qvd_Raw\Agresso"
$CopyDestination = "C:\Dest\Qlikview Storage\PrivateData\Gemensamma\Qvd_Raw\Agresso"
$files = Get-ChildItem -File "*.qvd" $CopySource -Force
foreach ($file in $files) {
Copy-Item -path $CopySource\$_$file -Destination $CopyDestination -Force
}
$CopySource = "C:\Source\Qlikview Storage\PrivateData\Gemensamma\Qvd_Raw\Agresso"
$CopyDestination = "C:\Dest\Qlikview Storage\PrivateData\Gemensamma\Qvd_Raw\Agresso"
$items = Get-ChildItem -File "*.qvd" $CopyDestination
foreach($I in $Items) {
$newfilename= rename-item -path $I.Name -newname ("Agresso_" + $I.Name)
The problem I have is that I need to copy files from source to destination and once they are over they need to have agresso_ added. Then they day after a batch of files will be copied again and also they need to be renamed to agresso_ and overwrite the old ones, preferably with move-item. I got a problem already, as I am not used with prefixes,
I tried enless of versions with where-object and simular, could not figure out a way to use test-path either.
I did exactly this but with renaming the files, like this for maximo:
$files = Get-ChildItem -File "*.qvd" $CopySource -Force
foreach ($file in $files) {
Copy-Item -path $CopySource\$_$file -Destination $CopyDestination -Force -Verbose 4>&1 |
Out-File -Append $logpath
}
"Klar med Kopiering av .qvd filer $global:currenttime" | Out-File $logpath -Append
"Påbörjar omdöpning av .qvd filer $global:currenttime" | Out-File $logpath -Append
$items = Get-ChildItem -File "*.qvd" $CopyDestination
foreach($I in $Items) {
$newfilename=$I.Name.Replace("QVDLager1","Maximo")
Move-Item -Path $I.FullName -Destination $CopyDestination\$newfilename -Force -Verbose 4>&1 |
Out-File -Append $logpath
If anyone can help me in the right direction it would be highly appriciated.
You can copy (or move) and rename the destination at the same time:
$CopySource = "C:\Source\Qlikview Storage\PrivateData\Gemensamma\Qvd_Raw\Agresso"
$CopyDestination = "C:\Dest\Qlikview Storage\PrivateData\Gemensamma\Qvd_Raw\Agresso"
Get-ChildItem -Path $CopySource -File "*.qvd" -Force | ForEach-Object {
# create the full path for the target file with "Agresso_" prefixed
$target = Join-Path -Path $CopyDestination -ChildPath ('Agresso_{0}' -f $_.Name)
$_ | Copy-Item -Destination $target -WhatIf
}
If satisfied with the results of the code shown in the console, you can remove the -WhatIf switch to really start copying (or moving) the files.

How can I delete files older than x days?

I want to delete files older than x days, 5 in the below example. I tried to use below, but its not working nor its throwing an error.
Get-ChildItem –Path “E:\del” –Recurse | Where-Object{$_.CreationTime –lt(Get-Date).AddDays(-5)} | Remove-Item
Here is an approach you could take.
$Path = E:\del
$DaysBack = "-5"
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($DaysBack)
#delete files from $Path directory that are older than $Daysback
Get-ChildItem -Path $Path -Include * -Recurse | Where-Object {$_.LastWriteTime -lt $DatetoDelete} | Remove-Item -ErrorAction SilentlyContinue -Recurse -Force
Try this:
$cleanup_days = 5
$cleanup_lastWrite = $now.AddDays(-$cleanup_days)
Get-ChildItem -Path "E:\del" | Where-Object { $_ -is [System.IO.FileInfo] } | ForEach-Object {
If ($_.LastWriteTime -lt $cleanup_lastWrite)
{
Remove-Item $("E:\del\" + $_)
}
}

How I can compare and move data from A to B in Powershell older than x Days?

I have a Problem with my Powershell Script. ;(
I want to delete/ move/ compare with Powershell.
Here my Idea:
If I start the Script I remove all empty folder from A. After that I want Move all Data from A to B that x Days older. (Here is my first problem)
If I make copy it works fine.
A other Idea is to compare A and B and only the diffrend to copy or move. (But I don't know how I can do this)
Here is my Code:
function removeFiles($source,$destination){
$elements = Get-ChildItem $source -Recurse
foreach($element in $elements){
if(($element.PSIsContainer) -and (!(Get-ChildItem -Recurse -Path $element.FullName))){
Write-Host "DELETE: " $element.FullName
Remove-Item $element.FullName -Confirm:$false
}
}
}
function copyFiles($source,$destination,$days){
$elements = Get-ChildItem $source -Recurse
$lastwrite = (Get-Date).AddDays(-$days)
foreach($element in $elements){
if($element.creationTime -le $lastwrite){
$targetFile = $destination + $element.FullName.SubString($source.Length)
if($element.PSIsContainer){
Write-Host "COPY FOLDER : " $element.FullName
Copy-Item $element.FullName -Destination $targetFile
}else{
Write-Host "COPY FILE : " $element.FullName
Copy-Item $element.FullName -Destination $targetFile
}
}
}
}
function moveFiles($source,$destination,$days){
Get-ChildItem -Path $source -Recurse | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-2)} | Move-Item -Destination $destination
}
CLS
$Source = "C:\Users\tarasov_w\Downloads"
$Destination = "C:\Users\tarasov_w\Desktop\ps_test"
$LogFile = "C:\Users\tarasov_w\Desktop\$(get-date -format 'MMddyyyy').txt"
$Days = 1
Start-Transcript $LogFile -noclobber
Write-Host "Start..."
removeFiles -source $Source -destination $Destination
#copyFiles -source $Source -destination $Destination -days $Days
moveFiles -source $Source -destination $Destination -days $Days
Write-Host "Fertig!"
UPDATE:
function compareFiles($source,$destination){
$folderA = Get-ChildItem $source -Recurse
$folderB = Get-ChildItem $destination -Recurse
$diff = Compare-Object -ReferenceObject $folderA -DifferenceObject $folderB -PassThru
foreach($element in $diff){
$element_fullname = $element.FullName
if($element.PSIsContainer){
# ????
}
}
}