通过Get-ChildItem仅忽略根目录中的文件

时间:2015-07-10 02:35:42

标签: powershell

我有一个非常简单的ASP.NET MVC应用程序目录结构,示例如下:

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

鉴于这种目录结构,我有一个小的Powershell脚本,可以复制[sourceDir]中的所有内容,忽略一些文件,并将其复制到[targetDir]

我遇到了第一步的问题,即使用[sourceDir] cmdlet复制Get-ChildItem中的所有内容。这是我的示例脚本(为简洁起见编辑):

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

问题是-Exclude参数排除了根目录中的web.config和views目录中的web.config。从技术上讲,它忽略了每个web.config;但是,我只想忽略根目录中的文件。

是否可以通过Get-ChildItem忽略根目录中的web.config?如果没有,我应该使用哪个cmdlet?

解决方案

正如所建议的那样,放弃Where Linq子句的-Exclude参数是正确的解决方案。我实际上有一个要忽略的文件数组,因此我使用了-NotIn运算符而不是-NotMatch示例脚本:

Get-ChildItem [sourceDir] -Recurse | 
     Where { $_.FullName -NotIn $_filesToIgnore } |
     Copy-Item -Destination [targetDir]

1 个答案:

答案 0 :(得分:2)

Get-ChildItem上的-Exclude参数是一个臭名昭着的问题来源。试试这种方式:

Get-ChildItem [sourceDir] | 
    Where {$_.FullName -notmatch "$sourceDirVar\\web\.config"} | 
    Copy-Item -Destination [targetDir] -Recurse