My folder structure looks like this:
AK_Data |--->2020-01-22-------|----->a.txt
| |----->b.txt
| |------>c.tf.err
|
|--->2021-01-15-------|----->d.txt
| |----->b.txt
| |------>x.tf.err
|
|--->2022-01-08-------|----->dv.txt
| |----->pq.bat
|
|--->2022-05-08-------|----->xyz.pdf
AK_Data
is the first folder which consists of multiple subfolders
like (2020-01-22,2021-01-15.....)
and these each subfolders contains 1000
of their different format files.
I need to go into each folder and delete all the files except those files having ".tf.err"
in their names. I have used $specificdate='2022-01-01'
means the files of the folder less than 2022-01-01
only needs to be deleted. So my expected output is:
AK_Data |--->2020-01-22-------|------>c.tf.err
|
|
|
|--->2021-01-15-------|------>x.tf.err
|
|
|
|--->2022-01-08-------|----->dv.txt (this folder will be untouched since>2022-01-01)
| |----->pq.bat
|
|--->2022-05-08-------|----->xyz.pdf (this folder will be untouched since>2022-01-01)
I only need to delete the files inside the folder, not the folder.
The powershell I used for this is:
cls
$specificdate='2022-01-01'
$destination = 'Y:\Data\Retail\ABC\Development\ak\AK_Data'
$files = Get-ChildItem $destination
$exte='\.(bz2)|(.bat)|(.err)|(~)'
foreach ($f in $files){
$outfile = $f.FullName -notmatch $exte
if ($outfile){
if ($f.Name -lt $specificdate){
$allfiles=Get-ChildItem $f.FullName -Exclude *.tf.err* -Name | remove-item -whatif
}
}
}
It is not deleting the files.
CodePudding user response:
I would do this by first iterating the source folder path for directories with a name that can be converted to a datetime less than the datetime in variabe $specificDate
.
Then use Get-ChildItem
again inside these folders to find and remove files that do not have .tf.err
in their name:
$specificdate = [datetime]::ParseExact('2022-01-01','yyyy-MM-dd', $null)
$sourceFolder = 'Y:\Data\Retail\ABC\Development\ak\AK_Data\*'
Get-ChildItem -Path $sourceFolder -Directory |
Where-Object { [datetime]::ParseExact($_.Name,'yyyy-MM-dd', $null) -lt $specificdate } |
ForEach-Object {
Write-Host "Removing files from folder $($_.Name).."
Get-ChildItem -Path $_.FullName -File |
Where-Object { $_.Name -notlike '*.tf.err*' } |
Remove-Item -WhatIf
}
Again here, I added the -WhatIf
switch so you can first see what WOULD happen.
If you're OK with that, remove -WhatIf
and run the code again to actually delete the files