如果Powershell中不存在目录结构,请创建目录结构

use*_*851 1 powershell

我试图创建一个目录结构,如果它不存在于另一个位置.它工作正常,但我在名称中带括号的任何目录上都出错.我想我不得不以某种方式逃脱,但不知道如何.

脚本代码:

$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 $_ }
  }
Run Code Online (Sandbox Code Playgroud)

Sha*_*evy 5

这是一个更短的解决方案:

Copy-Item -Path $source -Destination $destination -Filter {$_.PSIsContainer} -Recurse -Force
Run Code Online (Sandbox Code Playgroud)