2

I have a PowerShell script that deletes files in directory including files in subdirectories. I need it to delete files in that directory only and not to delete files in subdirectories

Here is what I have:

    $DelFiles = get-childitem $DirectoryName -include $FileTemplate -recurse |where {$_.Lastwritetime -lt (date).AddDays(-$days)}

Any help would be appreciated

3 Answers 3

2

Just remove -recurse:

$DelFiles = get-childitem $DirectoryName -include $FileTemplate | where {$_.Lastwritetime -lt (date).AddDays(-$days)}
Sign up to request clarification or add additional context in comments.

4 Comments

I tried that and no files were deleted in directory and its subdirectories
Maybe there is something else in the script that needs to be also modified?
post the entire script please.
C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe C:\WINDOWS\Script\CleanupTest.ps1 -DirectoryName \\nighthawkxa\f$\temp\Misz_Cleanup_Test\ -FileTemplate . -Days 0 -Jobname %%JOBNAME
0

Powershell (v 2.0.-1.-1) has an interesting behavior

Get-ChildItem . -include *.txt

- will fail your expectation (will return zero matches)

Get-ChildItem .\* -include *.txt

- will produce proper-expected results. (will return all txt files in current dir)

It seem to be a part of it's design - see it's manual:

Get-Help Get-ChildItem -full

Perhaps you $DirectoryName has format like C:\111\, when for your datagrab you actually should provide something like C:\111\*

get-childitem C:\111\* -include *.txt

Hope that helps. ^_^

Comments

0

remove recurse and add -file

if you want remove only files in directory and subdirectory

 get-childitem $DirectoryName -recurse -File -Filter $FileTemplate | where {$_.Lastwritetime -lt (date).AddDays(-$days)} | Remove-Item -Force

if you want remove only files in directory and not subdirectory

 get-childitem $DirectoryName -File -Filter $FileTemplate | where {$_.Lastwritetime -lt (date).AddDays(-$days)} | Remove-Item -Force

14 Comments

Tried that unsuccessfully
what have you in $FileTemplate variable? Do you have files that matches the desired LastWriteTime?
file type .txt.
When I run this script with the command line that I provided above I get the followingWARNING: No files to delete:
C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe C:\WINDOWS\Script\CleanupTest.ps1 -DirectoryName \\nighthawkxa\f$\temp\Misz_Cleanup_Test\ -FileTemplate * .* -Days 0 -Jobname %%JOBNAME
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.