2017-07-26 68 views
1

目標是使用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)}} 

這似乎與單個文件夾一起工作,但是當我將多個文件夾添加到排除的目錄時,它似乎無法工作。可以做些什麼來排除多個文件夾?

+0

。它loooks like you want to use'$ _。basename' instead ..'where {{_。basename -notin $ dir -and $ _。psiscontainer -eq $ true}' – Kiran

回答

0

因爲$directory是一個數組,所以你應該看看匹配它的內容而不是它自己(它令人討厭的是powershell讓單元素數組被視爲像它們的內容一樣)。

你可以試試:

?{$directory -contains $_.fullname} 

相反的:

?{$_.fullname -notmatch $directory} 
+0

我假設?{$ directory -contains $ _。 fullname}檢查文件夾列表是否包含在$目錄中列出的文件夾,因此排除它們,我們必須使用?{$ directory -no tcontains $ _。fullname}。我試過使用這個,但這似乎並不奏效。它仍然複製每個文件夾,而不管$目錄的內容 –

+0

@stevesimon Yup,你是對的,我的壞。恥辱,這是行不通的!您是否嘗試過在PowerShell命令行中單獨修改名稱格式等,而不是一次運行整個腳本?也許,爲了幫助我們所有人,你可以發佈一個你的$目錄文件內容如何的例子,以防你犯了錯誤。 –

0

試試這個:

$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' } 
+0

我可以在複製時排除文件。問題是與文件夾,我似乎無法找到一種方法來排除多個文件夾被複制。 –

1
$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 

上面的代碼中不包括$排除數組中列出多個文件夾,其餘的內容複製到目標文件夾

+1

你有一個錯字。在最後一行,你應該有'$ files'而不是'$ source'。 – Alternatex

相關問題