使用PowerShell进行复制时排除多个文件夹
目标是使用PowerShell将文件夹和文件从路径复制到另一个路径。但是,我想排除某些文件和文件夹被复制。我可以将它们添加到排除列表使用PowerShell进行复制时排除多个文件夹
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}
我假设?{$ directory -contains $ _。 fullname}检查文件夹列表是否包含在$目录中列出的文件夹,因此排除它们,我们必须使用?{$ directory -no tcontains $ _。fullname}。我试过使用这个,但这似乎并不奏效。它仍然复制每个文件夹,而不管$目录的内容 –
@stevesimon Yup,你是对的,我的坏。耻辱,这是行不通的!您是否尝试过在PowerShell命令行中单独修改名称格式等,而不是一次运行整个脚本?也许,为了帮助我们所有人,你可以发布一个你的$目录文件内容如何的例子,以防你犯了错误。 –
试试这个:
$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' }
我可以在复制时排除文件。问题是与文件夹,我似乎无法找到一种方法来排除多个文件夹被复制。 –
$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
上面的代码中不包括$排除数组中列出多个文件夹,其余的内容复制到目标文件夹
你有一个错字。在最后一行,你应该有'$ files'而不是'$ source'。 – Alternatex
。它loooks like you want to use'$ _。basename' instead ..'where {{_。basename -notin $ dir -and $ _。psiscontainer -eq $ true}' – Kiran