Daniel Grima
Daniel Grima

Reputation: 2825

PowerShell Remove-Item exclude folder files

I have a simple script which is used to delete files from a folder. The script accepts two parameters:

  1. The path of the folder to delete from
  2. A list of items to be excluded from deletion

This is the script I have:

Param(
    [Parameter(Mandatory=$True)]
    [string]$pathDeleteFrom,
    [Parameter(Mandatory=$True)]
    [string[]]$excludeFiles
)

Remove-Item -path $pathDeleteFrom -exclude $excludeFiles -Recurse

I'm testing the script in a folder with the following structure:

enter image description here

Example (running the script for path "C:/test/files/*"):

What I'm failing to understand is, whether there's a way for me to exclude the "folder" and it's contents using wildcards.

I know that this is probably a simple question but I have tried searching online but failed to find an example similar to the scenario that I have.

Upvotes: 0

Views: 1319

Answers (1)

user1475623
user1475623

Reputation:

This should do what you're trying to accomplish... just fill in the blank and modify the condition statements to what you need.

$items = Get-ChildItem -Path "Directory Path" -Recurse

foreach($item in $items)
{
    if($item.name -like "*.TXT" -or $item.name -like "*.Json")
    {
        #CODE HERE
    }
    elseif(($item.GetType()).Name-eq "DirectoryInfo" -and $item.name -eq "Directory Name")
    {
        #CODE HERE
    }
}

Upvotes: 1

Related Questions