In a folder structure I have .stb files where name is unknown, and subfolders matching the name of the .stb file.
A folder can look like this:
C:\path\file1.stb
C:\path\file1\...
C:\path\file2.stb
C:\path\file2\..
The .stb file is tab delimited and look something like this:
Call ID Latitude Longitude Date and Time Noe
wasd 12.1241234 12.1243 2021-12-15 07:45:13.123 Noe
wasd 12.1241234 12.1243 2021-12-15 07:45:13.123 Noe
wasd 12.1241234 12.1243 2022-01-15 07:45:13.123 Noe
If a .stb contain a line where date is older than "$limit" the file and matching subfolder (and its content) should be deleted.
What I tested is:
$limit = (Get-Date).AddDays(-41).Date
$test = (Import-Csv -Path (Get-ChildItem -Path C:\Users\steff\Documents\ -Filter '*.stb').FullName -Delimiter "`t" | Where-Object { ([datetime]$_.'Date and Time') -lt $limit } )
But this only gives the output of file, and im not sure how to proceed to know what the actual filename is, in order to delte the .stb file and the matching subfolder. I am limited to Powershell here. Anyone know how to proceed?
CodePudding user response:
In this case, I would do a loop in which you can test if a .stb file indeed has such an older item and if so, you can construct the path for a subfolder with a similar name, test if that exists and if yes, delete that too.
Try
$limit = (Get-Date).AddDays(-41).Date
Get-ChildItem -Path 'C:\Users\steff\Documents' -Filter '*.stb' -File | ForEach-Object {
# test if the file contains an item with old date
$oldInfo = (Import-Csv -Path $_.FullName -Delimiter "`t") | Where-Object { ([datetime]$_.'Date and Time') -lt $limit }
if ($oldInfo) {
# create the path for a subfolder with the same basename as the file
$subFolder = Join-Path -Path $_.DirectoryName -ChildPath $_.BaseName
if (Test-Path -Path $subFolder -PathType Container) {
# a matching subfolder exists, delete it
Remove-Item -Path $subFolder -Recurse -WhatIf
}
# now delete the .stb file itself
Remove-Item -Path $_.FullName -WhatIf
}
}
The code above has -WhatIf
safety switches on both Remove-Item cmdlets. This is a safety measure, so you can first see in the console what would be deleted. Only if you are satisfied with that info, remove or comment out the -WhatIf
switches and run the code again.
CodePudding user response:
Try it like this:
$limit = (Get-Date).AddDays(-41).Date
$test = Get-ChildItem -Path C:\Users\steff\Documents\ -Filter '*.stb' | Import-Csv -Delimiter "`t" | Where-Object { ([datetime]$_.'Date and Time') -lt $limit } )