Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore only files in root directory via Get-ChildItem

Tags:

powershell

I have a pretty simple ASP.NET MVC application directory structure, a sample as follows:

root/
----- views/
---------- index.cshtml
---------- web.config
----- scripts/
---------- main.js
---------- plugin.js
----- web.config

Given this directory structure, I have a small Powershell script that copies everything in the [sourceDir], ignores a few files, and copies it to [targetDir].

I'm having an issue with the first step that copies everything in the [sourceDir] using the Get-ChildItem cmdlet. Here is my sample script (edited for brevity):

Get-ChildItem [sourceDir] -Recurse -Exclude web.config | Copy-Item -Destination [targetDir]

The problem is that the -Exclude parameter excludes the web.config in the root AND the web.config in the views directory. Technically, it ignores every web.config; however, I just want to ignore the file in the root.

Is it possible to ignore only the web.config in the root via Get-ChildItem? If not, which cmdlet should I use?

Solution

As suggested, abandoning the -Exclude parameter for a Where Linq clause was the correct solution. I actually had an array of files to ignore, so I used the -NotIn operator instead of the -NotMatch, sample script:

Get-ChildItem [sourceDir] -Recurse | 
     Where { $_.FullName -NotIn $_filesToIgnore } |
     Copy-Item -Destination [targetDir]
like image 440
Phil Scholtes Avatar asked Dec 29 '25 22:12

Phil Scholtes


1 Answers

The -Exclude parameter on Get-ChildItem has been a notorious source of problems. Try it this way:

Get-ChildItem [sourceDir] | 
    Where {$_.FullName -notmatch "$sourceDirVar\\web\.config"} | 
    Copy-Item -Destination [targetDir] -Recurse
like image 96
Keith Hill Avatar answered Jan 01 '26 14:01

Keith Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!