使用powershell复制时排除多个文件夹
目标是使用PowerShell将文件夹和文件从一个路径复制到另一个路径。但是,我想从复制中排除某些文件和文件夹。我可以通过将多个文件添加到排除列表来排除它们使用powershell复制时排除多个文件夹,powershell,get-childitem,copy-item,Powershell,Get Childitem,Copy Item,目标是使用PowerShell将文件夹和文件从一个路径复制到另一个路径。但是,我想从复制中排除某些文件和文件夹。我可以通过将多个文件添加到排除列表来排除它们 Get-ChildItem -Path $source -Recurse -Exclude "web.config","body.css","Thumbs.db" 用于排除我添加的文件夹 $directory = @("Bin") ?{$_.fullname -notmatch $directory} 最终的复制脚本如下所示 Get-
Get-ChildItem -Path $source -Recurse -Exclude "web.config","body.css","Thumbs.db"
用于排除我添加的文件夹
$directory = @("Bin")
?{$_.fullname -notmatch $directory}
最终的复制脚本如下所示
Get-ChildItem -Path $source -Recurse -Exclude "Web.config","body.css","Thumbs.db" | ?{$_.fullname -notmatch $directory} | Copy-Item -Force -Destination {if ($_.GetType() -eq [System.IO.FileInfo]) {Join-Path $dest $_.FullName.Substring($source.length)} else {Join-Path $dest $_.Parent.FullName.Substring($source.length)}}
这似乎适用于单个文件夹,但当我将多个文件夹添加到排除的目录中时,它似乎不起作用。如何排除多个文件夹?因为
$directory
是一个数组,您应该寻找与其内容相匹配的内容,而不是其本身(令人恼火的是,powershell允许将单元素数组视为其内容)
您可以尝试:
?{$directory -contains $_.fullname}
而不是:
?{$_.fullname -notmatch $directory}
试试这个:
$excluded = @("Web.config", "body.css","Thumbs.db")
Get-ChildItem -Path $source -Recurse -Exclude $excluded
在注释中,如果要排除文件夹,可以使用以下内容:
Get-ChildItem -Path $source -Directory -Recurse |
? { $_.FullName -inotmatch 'foldername' }
或者,您可以先检查容器,然后执行以下操作:
Get-ChildItem -Path $source -Recurse |
? { $_.PsIsContainer -and $_.FullName -notmatch 'foldername' }
上面的代码排除了$excludes数组中列出的多个文件夹,并将剩余内容复制到目标文件夹我假设?{$directory-contains$\ fullname}检查文件夹列表是否包含$directory中列出的文件夹,因此要排除它们,我们必须使用?{$directory-notcontains$\ fullname}。我尝试过使用它,但似乎不起作用。它仍然会复制每个文件夹,而不管文件夹的内容如何$directory@stevesimon是的,你说得对,我的错。可惜它不起作用!你有没有尝试过在powershell命令行中单独处理名称格式等,而不是一次运行整个脚本?也许,没有o帮助我们大家您可以发布一个示例,说明$directory文件内容的外观,以防您犯了错误。我可以在复制时排除文件。问题在于文件夹,我似乎找不到方法排除多个文件夹被复制。看起来您想改为使用
$\u.basename
。其中{$\.basename-notin$dir-和$\.psicontainer-eq$true}
您有一个输入错误。在最后一行您应该有$文件
,而不是$源
。
$source = 'source path'
$dest = 'destination path'
[string[]]$Excludes = @('file1','file2','folder1','folder2')
$files = Get-ChildItem -Path $source -Exclude $Excludes | %{
$allowed = $true
foreach ($exclude in $Excludes) {
if ((Split-Path $_.FullName -Parent) -match $exclude) {
$allowed = $false
break
}
}
if ($allowed) {
$_.FullName
}
}
copy-item $source $dest -force -recurse