Hi All, I’m a self thought an fairly new to Powershell so be gentle . I need to iterate through some folders and execute some commands in each folder. So far i have this but is stops at the first folder. Of all the things i am missing what exactly is the reason why it is not iterating. thx
Function Start-Cleanup ($folder){
$z = (Get-ChildItem -File $folder\*.zip | Measure-Object | Select-Object -ExpandProperty Count)
$c = (Get-ChildItem -File $folder\*.conf | Measure-Object | Select-Object -ExpandProperty Count)
if ($z -lt 3){
Write-Output "$folder Less or 3 backup available, nothing to do "
break
}
else {
Write-Output "$folder Removing old files"
Get-ChildItem $folder\*.zip | Where-Object -Property LastWriteTime -lt (Get-Date).AddDays(-60) | Remove-Item -force
}
if ($c -lt 3){
Write-Output "$folder Less or 3 config backups available, nothing to do"
break
}
else {
Write-Output "$folder Removing old config files"
Get-ChildItem $folder\*.conf | Where-Object -Property LastWriteTime -lt (Get-Date).AddDays(-60) | Remove-Item -force
}
}
$target = Get-ChildItem -Directory "C:\tempL"
foreach ($i in $target){
Start-Cleanup $i
}
Thanks for your reply laage. apparently there are more things wrong here… . I can tell you that i only need items in subfolder of tempL. When i do write-output i get all the folders listed.
for testing i removed the first folder and upon running script again it seemed to run on all the others.
C:\tempL\K11392 Removing old files
C:\tempL\K11392 Removing old config files
C:\tempL\K11546 Removing old files
C:\tempL\K11546 Less or 3 config backups available, nothing to do
It might not make a big difference for this particular case but when you do something like this in a larger environment it could become relevant.
In your little function you query the same folder up to 4 times. That could be quite time consuming and is actually unnecessary.
Something liket his should run a little faster I’d expect:
Function Start-Cleanup ($folder) {
$FileInventory = Get-ChildItem -Path $folder -File
$ZipInventory = $FileInventory | Where-Object -Property Extension -EQ -Value '.zip'
$ConfInventory = $FileInventory | Where-Object -Property Extension -EQ -Value '.conf'
if ($($FileInventory.Count) -lt 3) {
Write-Output "$folder Less or 3 backup available, nothing to do "
}
else {
Write-Output "$folder Removing old files"
$ZipInventory | Where-Object -Property LastWriteTime -lt (Get-Date).AddDays(-60) | Remove-Item -Force
}
if ($($ConfInventory.Count) -lt 3) {
Write-Output "$folder Less or 3 config backups available, nothing to do"
}
else {
Write-Output "$folder Removing old config files"
$ConfInventory | Where-Object -Property LastWriteTime -lt (Get-Date).AddDays(-60) | Remove-Item -Force
}
}
You query the folder only once and work with the collected data later on.