Alex Kibler
Alex Kibler

Reputation: 4954

How can I delete all of the contents of a directory (including subdirectories) except one subdirectory?

I'm trying to write an automated build and deploy script using PowerShell 2 for my angular2 app, but seeing as how our ASP.NET Web API lives in api/, I want to delete all of the old angular code without touching the API.

Here's what I've got so far:

Get-ChildItem -Path  $destination -Recurse -exclude somefile.txt |
Select -ExpandProperty FullName |
Where {$_ -notlike $destination+'\api*'} |
sort length -Descending |
Remove-Item -force -recurse

$destination is the directory where the app gets installed.

Quick folder tree in case I wasn't clear above:

$destination
    api\
    app\
    assets\
    vendor\
    index.html
    main.js
    system-config.js

As above, I want to delete everything but api\

Upvotes: 3

Views: 13093

Answers (1)

rrirower
rrirower

Reputation: 4590

I don’t have access to PowerShell 2. But, using PowerShell 3 (and later versions), you should be able to simplify your code by using something like this:

$path = "C:\test path"
Remove-Item $path -recurse -Exclude "api"

I created the same folder structure you specified assuming that api, app, assets, and vendor are sub-folders. I ran the script in the PowerShell IDE and it removed everything under the test path except for the api folder. I would assume that PowerShell 2 supports the same parameters on the command.

Upvotes: 5

Related Questions