Home > Enterprise >  Deleteing specific file type from 2 directory levels up
Deleteing specific file type from 2 directory levels up

Time:04-12

I am trying to figure out a way to make a script to remove files of a specifc type from multiple folders without removing it from the 1st directory. See below for an example.

Target file extention is .xlsm

The files to be deleted are located 2 directory levels up. But I need to skip the filetype located 1 directory level up

e.g.

\User Folder\Folder1\test.xlsm this needs to be kept
\User Folder\Folder1\SubFolder1\File.xlsm This must be deleted 
\User Folder\Folder2\foo.xslm this needs to be kept
\User Folder\Folder2\Subfolder2\bar.xlsm This must be deleted

CodePudding user response:

The Get-ChildItem cmdlet can take wildcards in its search path.

Try

Get-ChildItem -Path 'X:\User Folder\*\*\*' -File -Filter '*.xlsm' | Remove-Item -WhatIf

Remove the -WhatIf safety switch if what is shown in the console is correct and run again

CodePudding user response:

Maybe try to do a get-childItem of Folder1 in a variable. Then keep only folder in this variable. And finally do your cd/set-location for delete xlsm file.

Example (I haven't try but the form is normally good) :

$VarFolder = Get-ChildItem ...\Folder1\
foreach ($item in $VarFolder){if ($(get-item $item).Attributes -eq "Directory"){$VarKeeping  = $item }}

Then next of treatement with cd and remove..

  • Related