• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 921
  • Last Modified:

powershell where subfolder contains string

Hi

I need to write a powershell script to remove files older than a certain date but only from sub folder with the name "working" in it

I have found the code below but just need to modify for the folder name

any help is greatly appreciated

code from - http://www.winblogs.net/index.php/2009/10/01/delete-files-older-from-in-powershell/ 



a
Function GetOldFile
{
$Days = "0"
$TargetFolder = "d:\"
if (Test-Path $TargetFolder)
{
$Now = Get-Date
$LastWrite = $Now.AddDays(-$days)
$Files = get-childitem $TargetFolder -include *.john -recurse |Where {$_.LastWriteTime -le "$LastWrite"}
foreach ($File in $Files)
{write-host "Deleting file $File" -foregroundcolor "Red"; Remove-Item $File | out-null}
}
Else
{Write-Host "Folder $TargetFolder doesnt exist! Recheck the folder path!"}
}
GetOldFile

Open in new window

0
wbcintsol
Asked:
wbcintsol
1 Solution
 
Meir RivkinFull stack Software EngineerCommented:
try this code:
Function GetOldFile
{
	$Days = "0"
	$TargetFolder = "d:\"
	if (Test-Path $TargetFolder)
	{
		$Now = Get-Date
		$LastWrite = $Now.AddDays(-$days)
		$Folders = get-childitem $TargetFolder -include *working* -recurse |Where {$_.psIsContainer -eq $true}
		foreach ($Folder in $Folders)
		{
			write-host "Folder - $Folder" -foregroundcolor "Red"
			$Files = get-childitem $Folder | Where {$_.LastWriteTime -le "$LastWrite"}
			foreach ($File in $Files)
			{
				write-host "Deleting file $File" -foregroundcolor "Red"
				Remove-Item $File | out-null
			}
		}
	}
	Else
	{
		Write-Host "Folder $TargetFolder doesnt exist! Recheck the folder path!"
	}
}

GetOldFile

Open in new window

0
 
wbcintsolAuthor Commented:
Perfect - Thanks
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now