1

I am trying to create a directory structure if it doesn't exist in another location. It works, but I get an error on any directory with a bracket in the name. I assume I have to escape that somehow, but don't know how.

Script code:

$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 $_ }
  }
5
  • "It works, but I get an error." Does that mean it works besdies the places where there is an error, or that even bracket directories work fine, there is just error text written? If the latter, just add -ErrorAction SilentlyContinue to the cmdlet which is throwing the un-useful error. Commented Sep 16, 2012 at 17:33
  • Works for me without an error. What is the error you're getting? Please add the output of $error[0].exception.tostring() to your post. Commented Sep 16, 2012 at 17:39
  • If a directory with a bracket in the name already exists, it tries to create it again and I get an error: New-Item : Item with specified name C:\scrap\data\Evernote\backup\Untitled note [2]_files already exists. At C:\data\PowerShell\Untitled5.ps1:9 char:67 + ForEach-Object {if (!(Test-Path -path $_ )) { $null = New-Item <<<< -ItemType Container -Path $_ }} + CategoryInfo : ResourceExists: (C:\scrap\data\E... note [2]_files:String) [New-Item], IOException + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand Commented Sep 16, 2012 at 18:05
  • Weird. This shouldn't be happening, since you check with Test-Path before trying to create the directory. What do you get when you manually run Test-Path and New-Item with the path that raises the error? Commented Sep 16, 2012 at 19:04
  • Test-Path -path "C:\scrap\data\Evernote\backup\Untitled note [2]_files" return false...which is not right. It does exist. Commented Sep 16, 2012 at 19:13

2 Answers 2

5

Here's a shorter solution:

Copy-Item -Path $source -Destination $destination -Filter {$_.PSIsContainer} -Recurse -Force
Sign up to request clarification or add additional context in comments.

Comments

2

Got it. The error is due to the square brackets. They're used for pattern matches (see here), so Test-Path actually checks for

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

which doesn't exist. You have to use -LiteralPath to avoid this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.