我创建了一个简单的Powershell脚本,以在部署过程中将文件从目标目录复制到源目录,并且我想排除文件列表。但是需要注意的是,我希望能够仅在指定的子目录中排除文件。这是我用来执行复制并排除文件列表的代码段:
$SourceDirectory = "C:\Source"
$DestinationDirectory = "C:\Destination"
$Exclude = @("*.txt*", "*.xml*")
Get-ChildItem $SourceDirectory -Recurse -Exclude $Exclude | Copy-Item -Destination {Join-Path $DestinationDirectory $_.FullName.Substring($SourceDirectory.length)}
这将排除指定的文件出现在目录树中的任何位置。我想使用“排除”列表的地方是这样的:
$Exclude = @("*Sub1\.txt*", "*.xml*").
这将仅在Sub1文件夹下排除.txt文件,而整个范围内将排除.xml文件。我知道这是行不通的,但是我希望它有助于更好地证明我要解决的问题。
我已经考虑过使用多维数组,但是我不确定这是否过大。任何帮助,将不胜感激。
最佳答案
这是做到这一点的一种方法
$SourceDirectory = 'C:\Source'
$DestinationDirectory = 'C:\Destination'
$ExcludeExtentions = '*.txt*', '*.xml*'
$ExcludeSubDirectory = 'C:\Source\bad_directory1', 'C:\Source\bad_directory2'
Get-ChildItem $SourceDirectory -Recurse -Exclude $ExcludeExtentions |
Where-Object { $ExcludeSubDirectory -notcontains $_.DirectoryName } |
Copy-Item -Destination $DestinationDirectory
您最好的 friend 是
Where-Object
或where
。它以脚本块为参数,并使用该脚本块来验证通过管道的每个对象。只有使脚本返回$true
的对象才通过Where-Object
传递。另外,看看代表您从
Get-ChildItem
获得的文件的对象。它的Name
,Directory
和DirectoryName
分别包含已分割的文件FullName
片段。 Directory
实际上是代表父目录的对象,而DirectoryName
是字符串。 Get-Member
commandlet将帮助您发现类似的隐藏 gem 。
关于file - 将文件从源目录复制到目标目录,并从指定目录中排除特定文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18771291/