user310291
user310291

Reputation: 38190

Powershell delete all folders except one

I tried

Get-ChildItem -Path  'C:\temp' -Recurse Select Name | Where {$_ -notlike 'C:\temp\one*'} | sort length -Descending | Remove-Item -force 

but it doesn't work

Get-ChildItem : A positional parameter cannot be found that accepts argument 'Name'

What's wrong

Upvotes: 2

Views: 2888

Answers (3)

vvvv4d
vvvv4d

Reputation: 4095

You were missing a |

Get-ChildItem -Path  'C:\temp' -Recurse | Select -ExpandProperty FullName | Where {$_ -notlike 'C:\temp\one*'} | Remove-Item -force 

Upvotes: 3

Atul Gupta
Atul Gupta

Reputation: 9

Use the function below:

Function Delete-Except
{
$path = ""
$exceptions = @(
#Enter files/folders to omit#
)
try:
Get-ChildItem $source -Exclude $exceptions| Remove-Item $_ -Force -Recurse
catch:
Write-Host "Delete operation failed." - Foregroundcolor Red
Pause
}

Upvotes: 1

wasif
wasif

Reputation: 15478

Try this with -Exclude (And why sort when deleting files?)

Get-ChildItem -Path  'C:\temp' -Recurse -Exclude 'C:\temp\one*' | Remove-Item -force

Upvotes: 2

Related Questions