2012-09-16 132 views
1

我想創建一個目錄結構,如果它不存在於另一個位置。它可以工作,但是在名稱中帶有括號的任何目錄中都會出現錯誤。我想我必須以某種方式逃避,但不知道如何。創建目錄結構,如果它不存在Powershell

Script代碼:

$source = "c:\data" 
$destination = "c:\scrap\data" 

Get-ChildItem -Path $source -Recurse -Force | 
    Where-Object { $_.psIsContainer } | 
    ForEach-Object { $_.FullName -replace [regex]::Escape($source), $destination } | 
    ForEach-Object { 
    if (!(Test-Path -path $_)) { $null = New-Item -ItemType Container -Path $_ } 
    } 
+0

「它的工作原理,但我得到一個錯誤。」這是否意味着它的工作* besdies *有錯誤的地方,或即使括號目錄工作正常,只有錯誤文本寫入?如果是後者,只需將'-ErrorAction SilentlyContinue'添加到拋出無用錯誤的cmdlet中即可。 – latkin

+0

適合我,沒有錯誤。你得到的錯誤是什麼?請將'$ error [0] .exception.tostring()'的輸出添加到您的帖子中。 –

+0

如果名稱中包含一個括號的目錄已經存在,它會嘗試再次創建並且出現錯誤: 'New-Item:具有指定名稱C:\ scrap \ data \ Evernote \ backup \ Untitled note的項目[2] _文件已經存在。 在C:\ data \ PowerShell \ Untitled5.ps1:9 char:67 + ForEach-Object {if(!(Test-Path -path $ _)){$ null = New-Item <<<< -ItemType Container (C:\ scrap \ data \ E ... note [2] _files:String)[New-Item],IOException + FullyQualifiedErrorId:DirectoryExist,Microsoft.PowerShell.Commands .NewItemCommand' – user1612851

回答

2

明白了。錯誤是由於方括號。他們使用模式匹配(見here),所以實際上Test-Path檢查

C:\scrap\data\Evernote\backup\Untitled note 2_files

不存在。你必須使用-LiteralPath來避免這種情況。

5

這裏有一個較短的解決方案:

Copy-Item -Path $source -Destination $destination -Filter {$_.PSIsContainer} -Recurse -Force 
相關問題